Merging arrays and removing duplicates with Javascript

M

When you have two different JavaScript arrays and merge them into one, it’s important that you don’t have the same element in there more than once. Here are two different ways to concatenate arrays while removing duplicates.

1. A loop and check if the element is already in the array
2. Using the ECMA 6 function called Set

Interestingly enough the performance of these approaches differ based on how many items are in the array. Solution one – looping the array is much faster when there are less than 400 items; however, when there are more, using the Set function is over 50 to 100% faster. Actually, the larger the arrays the faster the Set operation is compared to looping.

Concatenate two arrays using Set function:
var uniqueArray = [new Set([array1 ,array2])];

Merging arrays by looping through the array:

[code]
for (var i = 0; i < array2.length; i++) {
if (array1.indexOf(array2[i]) === -1) {
array1.push(array2[i]);
}
}
[/code]

To extend this one step further let’s add the function to Prototype with Javascript to simplify the usage:

[code]
// Extend the Array property using a for loop
Array.prototype.concatenateUnique = function (array2) {

for (var i = 0; i < array2.length; i++) {
if (this.indexOf(array2[i]) === -1) {
this.push(array2[i]);
}
}

return this;

}

// Extend the Array property using the Set function`
Array.prototype.concatenateUnique = function (array2) {

return [new Set([array1 ,array2])];

}
[/code]

About the author

By Jamie

My Books