I try to create a new multidimensional array from another multidimensional array. The first array looks like the following:
array[0][0] = foo
array[0][1] = foo2
...and so on
array[1][0] = 123
array[1][1] = 234
...and so on
array[2][0] = blue
array[2][1] = red
...and so on
array[3][0] = fish
array[3][1] = bird
...and so on
…then I have an array called ‘results’ that contains of numbers (e.g. 1, 20 , 23). What I want to do is to create a new multidimensional array, just like the first, one but only with the elements from the first one that’s to be found as numbers in the array ‘results’.
Below is my try so far that doesn’t work. When I run the code I get the following error message:
Uncaught TypeError: Cannot set property '0' of undefined) <- line 5
What am I doing wrong?
1: var newArray = [];
2:
3: for (var i = 0; i < results.length; i++) {
4: var index = results[i]
5: newArray[0][i] = array[0][index];
6: newArray[1][i] = array[1][index];
7: newArray[2][i] = array[2][index];
8: newArray[3][i] = array[3][index];
9: }
you always need to initialize the array:
like in this example:
newArray[12345]isundefined, and you want to treat undefined element as array. so before you can do that you need to initalize the subarray:Edit: