Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort an ES6 `Set`?

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?

like image 782
ericsoco Avatar asked Oct 12 '15 20:10

ericsoco


People also ask

Can you sort a JavaScript Map?

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.

How do I sort alphabetically in JavaScript?

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.


1 Answers

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

like image 85
Benjamin Gruenbaum Avatar answered Oct 17 '22 21:10

Benjamin Gruenbaum