Ifty's BlogThoughts & Ideas
Merging Arrays Without Duplicates
JavaScriptArray

Merging Arrays Without Duplicates

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.

Ifthe Kharul IslamIfthe Kharul Islam
··1 min read

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

Related Articles