Ad

Adding Values To Array In Another Array

- 1 answer

Let's say I have an array like this:

var someData = [ // count: 5

    [ something, something, something ], // count: 3
    [ something ], // count: 1
    [ something, something, something, something ],  // count: 4
    [ ], // count: 0
    [ something, something ] // count: 2
]; 

I need to make array like this:

var myArray = [];

var firstCount = someData.lenght; // count: 5

for( a = 0; a < firstCount; a++ ) {

    allObjects[a] = firstObject;


    var secondCount = someData[a].lenght; // each has different

    for( b = 0; b < secondCount; b++ ) {

        allObjects[a] = secondObject; 
    }
}

How Im expecting it to be:

allObjects = [

    [ firstObject, secondObject, secondObject ], // count: 3
    [ firstObject ], // count: 1
    [ firstObject, secondObject, secondObject, secondObject ], // count:  4
    [ ], // count: 0
    [ firstObject, secondObject ], // count: 2
];

I might have made few (format) mistakes in this example but I hope that my goal is clear - I need to push objects to array of objects that is already in array but it seems to replace the value instead adding new value into it.

What am I missing here?

Ad

Answer

I might be wrong, but from your expected result, it seems that you want to push it to second index of array. In that case, you can change your inner for loop to be

var secondCount = someData[a].lenght; // each has different

    for( b = 1; b < secondCount; b++ ) {

        allObjects[a][b] = secondObject; 
    }

Note the changes in b = 1 and allObjects[a][b]

Ad
source: stackoverflow.com
Ad