EN
JavaScript - merge two arrays and de-duplicate items
0
points
In this article, we would like to show you how to merge two arrays and remove duplicate items using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const array1 = ['A', 'B'];
const array2 = ['B', 'C'];
const array3 = array1.concat(array2)
.filter((item, index, array) => array.indexOf(item) === index);
console.log(array3);
Practical examples
1. Set based approach
In this example, we use Set
based approach to prevent item duplication while adding them to the result
array.
// ONLINE-RUNNER:browser;
const mergeArrays = (...arrays) => {
const result = [];
const blocker = new Set(); // prevents item duplication
for (const array of arrays) {
for (const item of array) {
if (blocker.has(item)) {
continue;
}
blocker.add(item);
result.push(item);
}
}
return result;
};
// Usage example:
const array1 = ['A', 'B'];
const array2 = ['B', 'C'];
console.log(mergeArrays(array1, array2)); // ['A', 'B', 'C']
2. Simple types approach
In this example, we use simple types to merge arrays without duplicates.
// ONLINE-RUNNER:browser;
const mergeArrays = (...arrays) => {
const result = [];
const blocker = {}; // prevents item duplication
for (const array of arrays) {
for (const item of array) {
if (blocker.hasOwnProperty(item)) {
continue;
}
blocker[item] = true;
result.push(item);
}
}
return result;
};
// Usage example:
const array1 = ['A', 'B'];
const array2 = ['B', 'C'];
console.log(mergeArrays(array1, array2)); // ['A', 'B', 'C']
Note:
This solution should be used when each item has the same type in the array, and the type is one of: boolean, number, or string.