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: To extend this one step further let's add the function to Prototype with Javascript to simplify the usage: Published on Jun 13, 2022 Tags: JavaScript
| Javascript Arrays Tutorial
| unique
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
for (var i = 0; i < array2.length; i++) {
if (array1.indexOf(array2[i]) === -1) {
array1.push(array2[i]);
}
}
// 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])];
}
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.