How can I sort an ES6 `Set`?
A set is not an ordered abstract data structure.
A Set
however always has the same iteration order - element insertion order [1], so when you iterate it (by an iterating method, by calling Symbol.iterator
, or by a for.. of loop) you can always expect that.
You can always convert the set to an array and sort that.
Array.from(new Set(["b","a","c"])).sort();[...(new Set(["b","a","c"]))].sort(); // with spread.
[1] forEach
and CreateSetIterator
In some cases it may be preferable to "sort" the set in-place, similar to array.sort()
, it can be done like this:
function sortSet(set) { const entries = []; for (const member of set) { entries.push(member); } set.clear(); for (const entry of entries.sort()) { set.add(entry); } return set;};sortSet(new Set([3,2,1]))// => Set(3) { 1, 2, 3 }
the simplest way to do it as.
console.log(new Set(['b', 'a', 'c'].sort()))//Set(3) {"a", "b", "c"}