Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Copy array items into another array

I have a JavaScript array dataArray which I need to drive into another array newArray. But I don't need newArray[0] to be dataArray. I need to push in every one of the items into the new array:

var newArray = [];

newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...


or even better:
var newArray = new Array (
dataArray1.values(),
dataArray2.values(),
// ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);


So now the new array contains every one of the values of the individual data arrays. Is there some shorthand like pushvalues accessible so I don't need to repeat over every individual dataArray, adding the things individually?
by

2 Answers

akshay1995
Use the concat function, like so:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).
kshitijrana14
Found an elegant way from MDN

var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];

// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

Or you can use the spread operator feature of ES6:

let fruits = [ 'apple', 'banana'];
const moreFruits = [ 'orange', 'plum' ];

fruits.push(...moreFruits); // ["apple", "banana", "orange", "plum"]

Login / Signup to Answer the Question.