Getting All Unique Values from an Array in JavaScript with Set

by Michael Szul on

I've been coding with JavaScript since the late 90's, and have seen the evolution of the language from piecemeal implementation in browsers, to a robust language capable of working on machine learning algorithms. What I've appreciated seeing over the last 5-10 years has the been JavaScript slowly evolving into a more powerful language with additional native types and base methods for unique operations.

In the past, if you wanted to get all the unique values from an array, you'd actually have to loop the array, pushing each value onto a new array, while comparing items to make sure that they don't already exist in the new array. It works. It's relatively fast. It just seems like a kludge.

Last week, I had the need to create a unique array from some values. I actually needed to take an array of objects, only return the name property within that object, and (since several objects might have the same name) make the array unique.

The amount of code for this is absolutely minuscule, which shows how much JavaScript is evolving as a language, promoting concise software design. For example, here is the resulting solution to my problem:

const unique = [...new Set(courses)];
      

In the above example, courses is an array with potentially multiple items that are identical. Imagine it was something like:

const courses = [
          "Psychology",
          "Psychology",
          "Psychology",
          "Psychology",
          "Biology"
      ];
      

The new Set() method creates a new collection of iterable objects specifically meant to contain unique values. By passing in the courses array, you are create a new collection of only the unique values in courses. This new set is an iterable collection, but it's not an array. In order to turn it back into an array, we use the spread operator (...) to expand the set into it's individual items, placing them inside of the square brackets syntax of an array.

So there you go… a single line of code for something that traditionally would have taken maybe four or five, and it looks a lot less like a looping kludge.

I'll be covering the Set() function (and resulting object) in more detail in our YouTube series I Don't Hate JavaScript Anymore. Stay tuned.