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:
xxxxxxxxxx
1
const array1 = ['A', 'B'];
2
const array2 = ['B', 'C'];
3
4
const array3 = array1.concat(array2)
5
.filter((item, index, array) => array.indexOf(item) === index);
6
7
console.log(array3);
In this example, we use Set
based approach to prevent item duplication while adding them to the result
array.
xxxxxxxxxx
1
const mergeArrays = (arrays) => {
2
const result = [];
3
const blocker = new Set(); // prevents item duplication
4
for (const array of arrays) {
5
for (const item of array) {
6
if (blocker.has(item)) {
7
continue;
8
}
9
blocker.add(item);
10
result.push(item);
11
}
12
}
13
return result;
14
};
15
16
17
// Usage example:
18
19
const array1 = ['A', 'B'];
20
const array2 = ['B', 'C'];
21
22
console.log(mergeArrays(array1, array2)); // ['A', 'B', 'C']
In this example, we use simple types to merge arrays without duplicates.
xxxxxxxxxx
1
const mergeArrays = (arrays) => {
2
const result = [];
3
const blocker = {}; // prevents item duplication
4
for (const array of arrays) {
5
for (const item of array) {
6
if (blocker.hasOwnProperty(item)) {
7
continue;
8
}
9
blocker[item] = true;
10
result.push(item);
11
}
12
}
13
return result;
14
};
15
16
17
// Usage example:
18
19
const array1 = ['A', 'B'];
20
const array2 = ['B', 'C'];
21
22
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.