lilymz
lilymz

Reputation: 387

fill an array with objects from other arrays

I have three arrays:

var arrayOne=[{obj1}, {obj2}, {ob3}];
var arrayTwo=[{obj4}, {obj5}, {obj6}];
var arrayThree=[{obj7}, {obj8}, {obj9}];

And I need to Know how to fill a new array with values from those arrays, like this:

var arrayFINAL=[{obj1}, {obj2}, {ob3}, {obj7}, {obj8}, {obj9}, {obj4}, {obj5}, {obj6}];

I thought it was something like this:

var arrayFINAL = new Array(arrayOne, arrayTwo, arrayThree);

But it seems to create an array an array's of arrays not an objects array. Anyone knows how to do this? thnks!

Upvotes: 3

Views: 2006

Answers (5)

alex
alex

Reputation: 490163

Your code...

var arrayFINAL = new Array(arrayOne, arrayTwo, arrayThree);

Will make an array arrayFINAL with three members, each of which is another array, like a multidimensional array.

If you want to create a new array with all three, use the concat() operator...

var arrayFinal = arrayOne.concat(arrayTwo, arrayThree);

jsFiddle.

If you want to push them all onto the original array, use...

arrayOne.push.apply(arrayOne, arrayTwo.concat(arrayThree));

jsFiddle.

Upvotes: 0

PitaJ
PitaJ

Reputation: 15012

var arrayFinal = arrayOne.concat(arrayThree,arrayTwo);

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

You may be interested in array_merge from PHJS - the behaviour you're looking for is identical to what PHP's array_merge does, and the PHPJS version does the same in JavaScript.

Upvotes: -1

JRaymond
JRaymond

Reputation: 11782

You're looking for Array concatenation

arrayFinal = arrayOne.concat(arrayTwo, arrayThree);

See here for documentation

Upvotes: 0

gdoron
gdoron

Reputation: 150253

var combinedArray = arrayOne.concat(arrayTwo, arrayThree);

MDN

Syntax
array.concat(value1, value2, ..., valueN)

Live DEMO

Upvotes: 3

Related Questions