In vanilla JavaScript, there are multiple ways to combine all elements of two arrays and returns a new array. You can either use the Array.concat()
method or the spread operator (...
) to merge multiple arrays.
The Array.concat()
takes in one or more arrays as input and merges all subsequent arrays into the first:
const fruits = ['Apple', 'Orange', 'Banana'];
const moreFruits = ['Kiwi', 'Lemon'];
// merge all fruits
const allFruits = fruits.concat(moreFruits);
console.log(allFruits);
// ['Apple', 'Orange', 'Banana', 'Kiwi', 'Lemon']
This method works in all modern browsers, and IE6 and above. You can also merge more than two arrays by using the Array.concat()
method:
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
let combined = [].concat(arr1, arr2, arr3);
console.log(combined); // [ 1, 2, 3, 4, 5, 6 ]
Notice the [].concat()
syntax we used in the above example to merge arrays. It is similar to the first example except that the input arrays are merged with an empty array.
If you only care about modern browsers, better to use the ES6 spread operator to merge the arrays:
const fruits = ['Apple', 'Orange', 'Banana'];
const moreFruits = ['Kiwi', 'Lemon'];
// merge all fruits
const allFruits = [...fruits, ...moreFruits];
console.log(allFruits);
// ['Apple', 'Orange', 'Banana', 'Kiwi', 'Lemon']
What if the arrays contain duplicate elements? There is no "built-in" way to remove duplicates in ECMAScript 5. However, you can use the ES6 Set object along with spread operator to filter out all duplicates:
const fruits = ['Apple', 'Lemon', 'Banana'];
const moreFruits = ['Kiwi', 'Lemon'];
// merge all fruits
const allFruits = [...new Set([...fruits, ...moreFruits])];
console.log(allFruits);
// ['Apple', 'Lemon', 'Banana', 'Kiwi']
This approach only works in modern browsers and Node.js. Take a look at this article to learn more about removing duplicates from an array in JavaScript.
To learn more about JavaScript arrays, check out this guide that explains in detail how JavaScript arrays work and how to use them to store multiple pieces of information in a single variable.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.