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
setout 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 arrayconst fruits1 = ["apples", "oranges"];//given second arrayconst fruits2 = ["oranges", "grapes", "guava"];//display the merged array after removing duplicatesconsole.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 arrayfruits1and pass the second arrayfruits2as 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 thissetto array and display the returned array.