Getting unique values in JavaScript arrays

Let’s tackle the classical problem of getting an array of unique values in a JavaScript array.

Method 1: ES5 Syntax

This method uses the inbuilt Array.prototype.filter method available as a part of ECMAScript 5.1 specification.

The filter method goes through each value in the array it is run upon, and passes (currentValue, index of currentValue in the array, and the array itself) as arguments. It returns an array of values at which the passed callback returns a ‘true’.

The ‘unique’ method gets those arguments for each iteration. It relies on the fact that the indexOf method would go through the entire array and return the index of the first match; the equality condition would thus only be true for the first occurrence of a value in the array.

Method 2: The cooler ES6 way!

ES6 introduced two new data structures: Map and set. We’ll use Set for our task here.

A set is a collection of values which can be iterated upon in the order of insertion. A value in the set may only occur once; it is unique in the set’s collection.

Be careful about the browser support for the new data structure and the equality rules it follows to calculate the equality between values.

I hope this was useful!