Categories
JavaScript Answers

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

Spread the love

To merge two arrays in JavaScript and de-duplicate items, we use the spread operator.

For instance, we write

const array1 = ["foo", "bar"];
const array2 = ["baz", "qux"];
console.log(Array.from(new Set([...array1, ...array2])));

to put all the items in array1 and array2 into a new array with the spread operator.

Then we create a new set from the array with the Set constructor to remove the duplicates.

And then we call Array.from with the set to convert it back to an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.