How to Merge Two Arrays in JavaScript and De-duplicate Items

In this tutorial, you will learn how to merge two Arrays in JavaScript. However, the methods depend on the version you’re using.

ES5 Version

This version uses the concat() method to merge two arrays:

Javascript array concat
let array1 = ['Nick', 'David']; let array2 = ['James', 'Jack']; let arr = array1.concat(array2); console.log(arr); // Nick, David, James, Jack

The concat() method merges two or more arrays not changing the existing arrays, but returns a new array.

To remove duplicates, the filter() method can be used:

Javascript array concat
let array1 = ['Jack', 'Nick']; let array2 = ['Nick', 'Jack']; let arr = array1.concat(array2); console.log(arr); // Jack, Nick, Nick, Jack // remove all duplicates: Jack, Nick let unique = arr.filter(function (item, index) { return arr.indexOf(item) === index; }); console.log(unique); // Jack, Nick

ES6 Version

This version uses the destructuring method for merging two Arrays.

Javascript merging two arrays
const array1 = ['John', 'David']; const array2 = ['Jack', 'James']; const array3 = [...array1, ...array2]; console.log(array3); // John, David, Jack, James

The push() method is an alternate way to merge two Arrays.

Javascript push method merging two arrays
const array1 = ['John', 'David']; const array2 = ['Jack', 'James']; array1.push(...array2); console.log(array1); // John, David, Jack, James

To remove duplicates, Set is used. The Set object is used to store unique values of primitive values or object references.

Javascript push method merging two arrays
const array1 = ['John', 'John']; const array2 = ['Jack', 'Jack']; const arr = [...array1, ...array2]; const unique = [...new Set(arr)]; // John, Jack console.log(unique);

Arrays

The JavaScript Arrays class is a global object used in the construction of arrays, which are high-level and list-like objects. You can use arrays for storing several values in a single variable. An array can be described as a unique variable that is capable of holding more than one value simultaneously.