JavaScript(JS) JS merge two arrays and remove duplicate items
To merge two arrays and remove duplicate items in JavaScript/JS, you can use the concat()
method to join the arrays, and then use a Set
object to remove duplicate items. Here's an example:
const arr1 = [1, 2, 3]; const arr2 = [3, 4, 5]; const mergedArr = [...new Set(arr1.concat(arr2))]; console.log(mergedArr); // Output: [1, 2, 3, 4, 5]Source:www.theitroad.com
In the above example, we first define two arrays arr1
and arr2
. We then merge these two arrays using the concat()
method and store the result in the mergedArr
variable.
To remove the duplicate items, we create a new Set
object from the merged array using the spread operator ...
, which automatically separates each element of the array into individual items. We then convert the Set
object back to an array using the Array.from()
method or the spread operator ...
.
This creates a new array with only unique elements, which is stored in the mergedArr
variable. Finally, we log the mergedArr
variable to the console to verify that the operation was successful.