new Set(['b', 'a', 'c']).sort()
throws TypeError: set.sort is not a function
. How can I sort a Set
to ensure a particular iteration order?
Use the sort() method to sort the keys in a Map, e.g. const sorted = new Map([... map1]. sort()) . The spread syntax (...) is used to get an array of the Map's entries, which we can sort using the sort method.
JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With