Sunday, October 6, 2024
Google search engine
HomeLanguagesJavascriptHow to merge two arrays and remove duplicate items in JavaScript ?

How to merge two arrays and remove duplicate items in JavaScript ?

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: 

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:

Javascript




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);


Output

[
  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:

Javascript




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);


Output

[
  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:

Javascript




let arr1 = [1, 5, 3];
let arr2 = [4, 5, 6];
let newArr = arr1.concat(arr2.filter((item) => arr1.indexOf(item) < 0));
console.log(newArr);


Output:

[ 1, 5, 3, 4, 6 ]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments