This past weekend, I was working on a little project while evaluating Vue.js and I came across a common problem that all of us end up having to deal with sooner or later, regardless of what framework we use - filtering for unique elements in an array.
ES2015 introduced a new data type called Set. This is a borrowed concept for when you want a little more structure than your native array. One specific feature that I will highlight is that Sets do not allow duplicate values. They are unique by design.
Let's try it out:
let x = new Set(); x.add(1); x.add(1); console.log(x.size); // output: 1
You'll see that the size is still
1 because it refuses to add duplicates. Note that there are not any errors thrown when you attempt to add a duplicate value. That makes it much easier for us when you're consuming data from an external source or flattening a multi-dimensional array.
That works pretty well for handling the unique constraint, but that doesn't give us a standard array back. For that, we'll need help from another new feature - Spread Operator, which is written as
.... Made popular by functional languages, the spread operator outputs the full iteration of the set. However, it has to be used from within the context of a standard array or object (another interesting topic for another time.)
Let's expand on the example from earlier:
let x = new Set(); x.add(1); x.add(2); const y = [...x]; console.log(y); // output: [1, 2]
In the example, we create a set with 2 elements. We then expand out the values into an array, which is provided as the value for a new
y. This looks fine when you use a data source that is already unique, but let's look at another example, which starts off as a standard array and uses that as the source for the
const x = [1, 1, 2, 2, 3, 3, 3]; const y = new Set(x); const z = [...y]; console.log(z); // output: [1, 2, 3]
Upon inspecting it, you'll see that it is your standard array that you are used to working with. We can deconstruct that to a simple function:
const uniqueArray = originalArray => [...new Set(originalArray)];
This is especially useful if you're using reduce functions to flatten a multi-dimensional array. Here is an example of that:
const unique = a => [...new Set(a)]; const x = [[1, 2, 3], [2, 3, 1], [3, 2, 1]]; const y = x.reduce((acc, val) => acc.concat(val)); const z = unique(y); console.log(z); // output: [1, 2, 3]
So there you have it - a very easy shortcut to uniqueness in JS arrays, all thanks to ES2015!