Javascript with ECMAScript 5 standard which is supported by most browsers now, you can use apply()
to append array1
to array2
.
var array1 = [3, 4, 5];
var array2 = [1, 2];
Array.prototype.push.apply(array2, array1);
console.log(array2); // [1, 2, 3, 4, 5]
Javascript with ECMAScript 6 standard which is supported by Chrome and FF and IE Edge, you can use the spread
operator:
"use strict";
let array1 = [3, 4, 5];
let array2 = [1, 2];
array2.push(...array1);
console.log(array2); // [1, 2, 3, 4, 5]
The spread
operator will replace array2.push(...array1);
with array2.push(3, 4, 5);
when the browser is thinking the logic.
Bonus point
If you'd like to create another variable to store all the items from both array, you can do this:
ES5 var combinedArray = array1.concat(array2);
ES6 const combinedArray = [...array1, ...array2]
The spread operator (...
) is to spread out all items from a collection.