About Me
cover

Merging Arrays Without Duplicates

9/23/2023, 12:00:00 AM

JavaScriptArray

Sometimes we need to merge 2 or more javascript arrays into one with unique values. Merging arrays in JavaScript using the spread operator is an easy task. For example:

const arr1 = [1, 3, 4];
const arr2 = [2, 3, 4, 5];
console.log([...arr1, ...arr2]);
// Output: [1, 3, 4, 2, 3, 4, 5]

But the above solution contains duplicate elements. If we want to avoid identical elements from our newly merged array we can use Javascript's Set. For example:

const arr1 = [1, 3, 4];
const arr2 = [2, 3, 4, 5];
console.log(...new Set([...arr1, ...arr2]));
// Output: 1, 3, 4, 2, 5
© 2024 | Ifty64bit | All Right Reserved.