Follow @endyourif rss Facebook LinkedIn

Merging arrays and removing duplicates with Javascript Merging arrays and removing duplicates with Javascript

Published on Jun 13, 2022

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:


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


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


// 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])];

}

Tags: JavaScript | Javascript Arrays Tutorial | unique

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP