How to merge two arrays in JavaScript and de-duplicate items?
How to Merge Two Arrays and De-duplicate Items in JavaScript
Merging two arrays in JavaScript can be done in a few different ways to get the desired result. Additionally, there is a way to de-duplicate items in JavaScript, which can be especially helpful when merging arrays.
Merging Arrays
There are several ways to merge two arrays in JavaScript, including use of the concat() method and the spread operator (…).
To use the concat() method, combine the two arrays as arguments and assign the new array to a variable:
let merged = array1.concat(array2);
To use the spread operator (…), combine the two arrays into a new array and assign the merged array to a variable:
let merged = [...array1,...array2];
De-duplicating Items
To de-duplicate items after merging two arrays, use the Set object:
let unique = [...new Set(merged)];
This will eliminate all items from the array that duplicate each other.
Additional Tips
- Be sure to check the type of data within each array, as the merging process may not work correctly if the data types are different (for example, merging a string array with a number array).
- The set() method requires ECMAScript 2015 ( also known as ES6 ) or higher to use and may not be supported on older browsers.
Merging two arrays and de-duplicating items in JavaScript can be easier than it may first seem. Using the methods described above and following a few simple tips can save time and make the process go smoother.