In this article, we will see how to merge two arrays and remove duplicate items from the merged array in JavaScript. While working with the arrays in JavaScript, we often used to merge and also remove the duplication of items from the new array.
There are some methods to merge two arrays and remove duplicate items, which are given below:
Table of Content
Method 1: Using Spread Operator and Set() Object
The Spread Operator is used to merge two arrays and then use the Set() object to remove the duplicate items from the merged array.
Example: This example shows the implementation of the above-explained approach.
let arr1 = [1, 2, 3, 4, 5, 6]; let arr2 = [3, 4, 5, 7]; let arr = [...arr1, ...arr2]; let mergedArr = [... new Set(arr)]
console.log(mergedArr); |
[ 1, 2, 3, 4, 5, 6, 7 ]
Method 2: Using concat() Method and Set() Object
The concat() method is used to merge two arrays and then use the Set() object to remove the duplicate items from the merged array.
Example: This example shows the implementation of the above-explained approach.
let arr1 = [1, 2, 3, 4, 5, 6]; let arr2 = [3, 4, 5, 7]; let arr = arr1.concat(arr2); let mergedArr = [... new Set(arr)]
console.log(mergedArr); |
[ 1, 2, 3, 4, 5, 6, 7 ]
Method 3: Using concat() Method and Filter()
The concat() method is used to merge two arrays and then use the filter is used to remove the duplicate items from the merged array.
Example: This example shows the implementation of the above-explained approach.
let arr1 = [1, 5, 3]; let arr2 = [4, 5, 6]; let newArr = arr1.concat(arr2. filter((item) => arr1.indexOf(item) < 0));
console.log(newArr); |
[ 1, 5, 3, 4, 6 ]
Method 4: Using Lodash _.union() Method
In this appproach, we are using the Lodash _.union() method that can take n numbers of arrays as parametres and return the union of those array with unique values.
Example: This example shows the implementation of the above-explained approach.
// Requiring the lodash library const _ = require( "lodash" );
// Use of _.union() method let gfg = _.union([1, 2, 3], [3, 4, 5],
[6, 2, 7]);
// Printing the output console.log(gfg); |
Output:
[1, 2, 3, 4, 5, 6, 7]