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.
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" ];
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
(Photo by Harshil Shah)