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.
A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.
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
🔍. Similar posts
Simplifying Layouts With React Fragments
18 Jan 2025
Stop Installing Node Modules on Your Docker Host - Install Them in the Container Instead
14 Jan 2025
An Easy to Understand React Component Introduction for Beginners
14 Jan 2025