3
Merge two (or more) Arrays and remove duplicate items.
2021-01-27 - JavaScript
1// JS Tip of the Day
2// Merge two (or more) Arrays and remove duplicate items.
3
4const firstArray = [2, 4, 6, 5], secondArray = [6, 11, 5, 3];
5const mergedArray = [...firstArray, ...secondArray];
6
7// Remove Duplicate Items with Filter method
8const uniqueItemsWithFilter = mergedArray.filter((val, pos) => {
9 return mergedArray.indexOf(val) === pos; // Remove return and brackets if you wish
10});
11
12// ...or remove Duplicate Items with Set and Destructuring
13const uniqueItemsWithSet = [...new Set(mergedArray)];
14
15console.log(uniqueItemsWithFilter); // [2, 4, 6, 5, 11, 3]
16console.log(uniqueItemsWithSet); // [2, 4, 6, 5, 11, 3]
#JStipoftheday