Three methods to get unique values from arrays in ES6.
Everistus Olumese
Posted on March 30, 2020
This article was originally published on everistus.me
There are several ways and several algorithms that you can easily implement to retrieve unique element in an array in JavaScript. In this article, we will discuss three of those ways. This is the first article in The JavaScript Snippet Series. It is accompanied by a video.
Using Set
In ES6, a Set is a collection of values. The values in a set are unique in the Set's collection. Using this property of a Set, we can pass an array into a Set and because each value in the Set has to be unique, the value equality will be checked. This means the Set will only retain unique values. We can, therefore, using the spread
operator return a new array of unique values.
const arr = [2019, 2020, 2019, 2018, 2020, 2021, 2030, 2020, 2019];
// Using sets
const useSet = arr => {
return [...new Set(arr)];
};
console.log(result);
This will return a new array with only unique elements like we wanted.
Using Array.filter
The next method we will be using is using ES6 Array.filter
function. The Array.filter
function takes a callback whose first parameter is the current element in the operation. It also takes an optional index
parameter and the array itself. Combining these, we can use Array.filter to ensure only unique element are returned in the array
// Using Array.filter
const useFilter = arr => {
return arr.filter((value, index, self) => {
return self.indexOf(value) === index;
});
};
const result = useFilter(arr);
This will give us the same result as before:
Using Iteration
The last method we will consider is using a for...of loop to iterate through the array and keep only unique elements in a new array.
// Using iteration
const useIteration = arr => {
const map = [];
for (let value of arr) {
if (map.indexOf(value) === -1) {
map.push(value);
}
}
return map;
};
const result = useIteration(arr);
We create a new array, simply loop through the initial array and then if the current element is not in the new array, we push it into the new array else, we leave it out. At the end of the iteration, we return the new array that contains unique values.
It also produces the correct result for us
That is three simple ways to return unique values in an array in ES6.
Note: We did not discuss the time and space complexity using these simple algorithms. If you would like to discuss it, why not add a comment either on the youtube page or on the comment below.
We will be discussing array sorting in the next episode of JavaScript Snippet Series. Hope to see you back here soon.
Posted on March 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.