How to Use Set in JavaScript ES6 to Find Unique Items

Need unique values in JavaScript? Thatā€™s where the Set object comes in. Hereā€™s how to use Set to filter a list of unique primitive values, objects by reference, or objects by their contents (values).

Dr. Derek Austin šŸ„³
Coding at Dawn
Published in
11 min readNov 4, 2020

--

Photo by Stephen Leonardi on Unsplash

Unique JavaScript Values? Think Set

A Set is a unique collection of items, and it has the advantage over JavaScript objects that you can iterate through the items of a Set in insertion order.

ā€œThe Set object lets you store unique values of any type, whether primitive values or object references.ā€ ā€” MDN Docs

In other words, you can loop through a Set like an array, and the items stay in the order that they were found in. The properties of a JavaScript object do not retain their insertion order, so the order the properties were added to an object is lost in translation if use try to filter unique items using an object.

Set is an ES6 feature supported in all modern browsers, including IE11, according to the page for Set() on CanIUse.com.

--

--

Dr. Derek Austin šŸ„³
Coding at Dawn

Hi, I'm Doctor Derek! I've been a professional web developer since 2005, and I love writing about programming with JavaScript, TypeScript, React, Next.js & Git.