Removing duplication is a common task when dealing with arrays in Javascript. In this tutorial, I will show you 4 dead simple ways to remove duplications in a JS array.
Now, let dive into it!
Sets
The Set
object lets you store unique values of any type, whether primitive values or object references.
const cars = ['audi', 'ford', 'tesla', 'ford', 'toyota', 'audi'];
function removeDuplicates(cars) {
return [...new Set(cars)];
}
console.log(removeDuplicates(cars));
// 👇🏽 See the output below
[ 'audi', 'ford', 'tesla', 'toyota', 'Bugatti' ]
Filter
The filter()
method of Array
instances creates a shallow copy* of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
As a result, when you change either the source or the copy, you may also cause the other object to change too. That behavior contrasts with the behavior of a deep copy, in which the source and copy are completely independent.
const cars = ['audi', 'ford', 'tesla', 'ford', 'toyota', 'audi', 'Bugatti']
function removeDuplicates(cars) {
return cars.filter((value, index) => cars.indexOf(value) === index)
}
console.log(removeDuplicates(cars))
// 👇🏽 See the output below
[ 'audi', 'ford', 'tesla', 'toyota', 'Bugatti' ]
Modifying Prototype
In JavaScript, the array prototype constructor allows you to add new properties and methods to the Array
object. The Array prototype is also like a set of methods and properties that all arrays inherit. So we can create a new method that will return a new set of array items, and just call it to remove duplications in our previous array.
const cars = ['audi', 'ford', 'tesla', 'ford', 'toyota', 'audi', 'Bugatti']
Array.prototype.unique = function() {
return Array.from(new Set(this));
}
function removeDuplicates(cars) {
return cars.unique()
}
console.log(removeDuplicates(cars))
// 👇🏽 See the output below
[ 'audi', 'ford', 'tesla', 'toyota', 'Bugatti' ]
Lodash
_.uniq
method of the lodash library produces a duplicate-free version of the array. We can also sort this array by passing the second parameter is true
.
import { _ } from 'lodash'
const cars = ['audi', 'ford', 'tesla', 'ford', 'toyota', 'audi', 'Bugatti']
function removeDuplicates(cars) {
return _.uniq(cars)
}
console.log(removeDuplicates(cars))
// 👇🏽 See the output below
[ 'audi', 'ford', 'tesla', 'toyota', 'Bugatti' ]
🎒 More resources
Learn more about Set
Learn more about Filter
Lodash Documentation
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium