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).
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.