Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Set in JavaScript guaranteed to be stable?

Tags:

javascript

set

Playing with Set, it appears to be stable (ie items remain in the order they are seen in):

> [...new Set(["foo", "bar", "foo", "foo", "baz", "bar"])]
["foo", "bar", "baz"]

But I can't find any documentation that says it is guaranteed to be stable.

like image 441
Chas. Owens Avatar asked Oct 22 '25 22:10

Chas. Owens


1 Answers

According to MDN you can iterate through the elements of a set in insertion order. The detailed documentation page of Set methods is full of "in insertion order" statements.

A test:

a = new Set()
a.add(1)
a.add(2)
a.add(4)
a.add(3)
console.log([...a]) // [1,2,4,3]

a.add(2) // already present element has no effect on order
console.log([...a]) // [1,2,4,3]
like image 166
Jan Stránský Avatar answered Oct 25 '25 13:10

Jan Stránský