How to Find & Remove Duplicates in JavaScript Arrays
In this tutorial, we'll discover different ways of finding duplicates within an array in JavaScript, as well as how to remove those duplicates.
Finding Duplicates
We can find duplicates within a JavaScript array by sorting the array first, then stepping through each index and running a value comparison. If a match is found, the index's value is pushed to a temporary array. Otherwise, we skip it and move onto the next array position until we've reached the end of the array:
var my_array = [1, 1, 2, 3, 4, 3, 5];
var duplicates = [];
my_array.sort();
for (var i = 0; i < my_array.length; i++) {
if (my_array[i] === my_array[i + 1]) {
duplicates.push(my_array[i]);
}
}
console.log(duplicates);
// result: [1, 3]
Removing Duplicates
There are a couple of different methods we can pursue when removing duplicate values from JavaScript arrays. The first method follows our duplication search functionality but, instead of pushing the duplicate values to a temporary array, we will just remove them from the existing array using the JavaScript splice()
method:
var my_array = [1, 1, 2, 3, 4, 3, 5];
my_array.sort();
for (var i = 0; i < my_array.length; i++) {
if (my_array[i] === my_array[i + 1]) {
my_array.splice(i, 1);
}
}
console.log(my_array);
// result: [1, 2, 3, 4, 5]
The shorthand method for removing duplicate values from an array can also be used and written by utilizing a Set()
, a JavaScript object that allows you to store unique values of any type:
var my_array = [1, 1, 2, 3, 4, 3, 5];
var cleaned_array = [...new Set(my_array)];
console.log(cleaned_array);
// result: [1, 2, 3, 4, 5]
Conclusion
Finding and removing duplicate values from JavaScript arrays is pretty straightforward, but does require some knowledge of how arrays work.
I've written another article about JavaScript array manipulation that you can also read to learn more about the JavaScript functions available for adding, updating, and remove array items.
Created: January 22, 2022
Comments
There are no comments yet. Start the conversation!