How to Remove Duplicates from an Array in JavaScript
Table of Contents
By default, arrays in JavaScript allow for duplicates, so it is up to you to not add a new element if it already exists in the array.
However, sometimes you start off with an array and need to remove all the duplicates.
In this post, we'll learn how to remove duplicates from an array in JavaScript.
Using a Set
A set in JavaScript is a new collection that stores only unique values in it.
Because every value must be unique in a set, if you try to pass it a duplicate entry, it will not be added.
We can use this to our advantage by creating a set and adding our entire array to it, then converting our set back to an array.
JAVASCRIPTconst array = [1, 2, 2, 3, 3, 3];
const set = new Set(array);
const uniqueArray = Array.from(set);
console.log(uniqueArray);
BASH[1, 2, 3]
Alternatively, you can use the spread operator:
JAVASCRIPTconst array = [1, 2, 2, 3, 3, 3];
const set = new Set(array);
const uniqueArray = [...set];
console.log(uniqueArray);
BASH[1, 2, 3]
Either way, we are now left with an array that only contains unique values by taking advantage of the fact that sets only allow for unique values.
Using Filter
Another way to remove duplicates is to use the filter
method.
We can just pass true
if the current value is unique, and false
if it is not.
JAVASCRIPTconst array = [1, 2, 2, 3, 3, 3];
const uniqueArray = array.filter((value, index) => {
return array.indexOf(value) === index;
});
console.log(uniqueArray);
BASH[1, 2, 3]
Because the indexOf
method will return the first instance the value appears, we can detect if a value is a duplicate because it will return an earlier index, instead of the one we're currently on.
When this happens, we reject this value and return false
.
In the end, you're left with an array of only unique values.
Conclusion
In this post, we looked at the two best ways to remove duplicates from an array in JavaScript.
You can either use a set and initialize it with the entire array, or use the filter
method to remove duplicates.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a MySQL Server using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js