How to merge two arrays in JavaScript and de-duplicate items

Overview

In this shot, we will learn how to merge two arrays and remove duplicates from them using JavaScript.

We will observe the following steps:

Steps:

  • We will concatenate the two arrays using the concat() method.
  • We will create the set out of the merged array, removing duplicates.
  • We will convert the set to an array and print the returned array.

Let's take a look at an example.

Example

// given first array
const fruits1 = ["apples", "oranges"];
//given second array
const fruits2 = ["oranges", "grapes", "guava"];
//display the merged array after removing duplicates
console.log(Array.from(new Set(fruits1.concat(fruits2))));

Explanation

In the above code snippet:

  • Line 2: We declare and initialize the first array fruits1.
  • Line 5: We declare and initialize the second array fruits2.
  • Line 8: We merge the two arrays using the concat() method on the first array fruits1 and pass the second array fruits2 as a second parameter. This will return the merged array. Next, we will pass this merged array to a set, which removes duplicates from it. Now, we will pass this set to array and display the returned array.

Free Resources