2

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: }

1 Answer 1

6

you always need to initialize the array:

newArray[0] = [];

like in this example:

var newArray = [];
// newArray[12345] is undefined
newArray[12345][2] = 3; // error!

newArray[12345] is undefined, and you want to treat undefined element as array. so before you can do that you need to initalize the subarray:

var newArray = [];
newArray[12345] = []; // now "newArray[12345]" is new subarray
newArray[12345][2] = 3;

Edit:

var newArray = [];

for (var i = 0; i <= 3; i++) {
    newArray[i] = []; 
    //newArray[i] = new Array(); - same thing
}

for (var i = 0; i < results.length; i++) {
    var index = results[i]
    newArray[0][i] = array[0][index];
    newArray[1][i] = array[1][index];
    newArray[2][i] = array[2][index];
    newArray[3][i] = array[3][index];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, so "for(var i = 0; i < 4; i++) { newArray[i] = []; }" should work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.