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?
asked Jan 18, 2016 at 1:51
Solo
7,0438 gold badges40 silver badges77 bronze badges
1 Answer 1
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]
Sign up to request clarification or add additional context in comments.
Comments
lang-js
array[i] = 'value'overwrites the value, if you want to add you eitherpush()orunshift()somethingandsecondObject, including an example function call.allObjects[a].push(secondObject)