How to get Unique Values from an Array using a Set in JavaScript
Arrays are a useful data structure because they allow you to store values in an ordered list.
However, because you control when elements are added, there are no guarantees that the values in the array are unique.
In this post, we'll learn how you can use a Set and its properties to your advantage to get unique values from an array in JavaScript.
How to get unique values from an array in JavaScript using a Set
First, let's create an array with duplicate values:
JAVASCRIPTconst array = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
Clearly, this array has duplicate values.
To get unique values from this array, we can use a Set.
A Set is a data structure that stores unique values. It is similar to an array, but it does not allow duplicate values.
To create a Set from an array, you can use the Set
constructor:
JAVASCRIPTconst set = new Set(array);
Once we have this set, we can convert it back into an array using the Array.from
method:
JAVASCRIPTconst uniqueArray = Array.from(set);
Let's put this all together:
JAVASCRIPTconst array = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
const set = new Set(array);
const uniqueArray = Array.from(set);
console.log(uniqueArray);
JAVASCRIPT[1, 2, 3, 4, 5]
Now if you want to do this in a single line, we can take advantage of the spread operator which will convert the set into an array for us:
JAVASCRIPTconst array = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);
JAVASCRIPT[1, 2, 3, 4, 5]
Conclusion
In this post, we learned how to get unique values from an array in JavaScript using a Set.
Simply create a Set from the array, and then convert it back into an array to get an array with only unique values.
Thanks for reading!
- Getting Started with TypeScript
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor