How to Merge Arrays in Vanilla JavaScript (ES5 and ES6)

You’ve previously learned how to add and remove items from an array by using JavaScript’s push() method.

But what if we want to add an array of items to an existing array? In other words, what if we want to merge two different arrays together?

To merge two or more arrays together in JavaScript, you can use the Array.prototype.push.apply()

Let’s say we have two fruit baskets, and we want all the fruits in one basket. Not a problem.

ES5


var fruitBasketOne = ['apple', 'banana', 'grapes'];
var fruitBasketTwo = ['orange', 'apricot', 'pear'];
Array.prototype.push.apply(fruitBasketOne, fruitBasketTwo);

// returns ['apple', 'banana', 'grapes', 'orange', 'apricot', 'pear']
console.log(fruitBasketOne)

// returns ["orange", "apricot", "pear"]
console.log(fruitBasketTwo)

This will merge the second array into the first. Notice that the second array, fruitBasketTwo still remains in memory. This method does not remove the original array.

Merging Arrays With ES6

Merging can be even easier, using the ES6 spread operator:


let fruitBasketOne = ['apple', 'banana', 'grapes'];
let fruitBasketTwo = ['orange', 'apricot', 'pear'];
fruitBasketOne.push(...fruitBasketTwo);

// returns ['apple', 'banana', 'grapes', 'orange', 'apricot', 'pear']
console.log(fruitBasketOne);

Compatibility

The first push method is compatible with all modern browsers, and back to at least IE6. The second method only works in modern browsers, but you can use a pre-processor like Babel to compile your JavaScript back to ES5 compatible code, and make work in older browsers.

More about the Array Push method.

No comments to display.