How to sort a Set in JavaScript

ES6 introduced the set data structure in JavaScript. But sets are not ordered abstract data structures. So there is no .sort() property available on them. To sort a Set in JavaScript, we need to convert it into an array first.

Since arrays are sortable, we will then sort them, and then convert the array back to a Set after we are done. At some point, the spec might add a sort method to Set() that does all of this by default, but for now, there are no alternatives.

- Advertisement -

Here is what it looks like code-wise:

const numbers = new Set([5, 4, 1]);

const sortedNumbersArray = Array.from(numbers).sort((a, b) => a - b);
const sortedNumbersSet = new Set(sortedNumbersArray);

console.log(sortedNumbersSet); //  {1, 4, 5}

Instead of the Array.from method, we can use destructuring (aka the spread operator) to create the array too:

const strings = new Set(['x', 'z', 'y']);

const sortedStringsArray = [...strings].sort();

const sortedStringsSet = new Set(sortedStringsArray);
console.log(sortedStringsSet); // {'x', 'y', 'z'}

Wrapping up

While converting a Set to an Array and then back is not an efficient solution, that is the best option currently to sort a Set in JavaScript. The EcmaScript standard does not have an OrderedSet data structure and that might change in the future, but until then, hope this solution helps.

Recent Articles

How to sort a Set in JavaScript

ES6 introduced the set data structure in JavaScript. But sets are not ordered abstract data structures. So there is no .sort() property...

Debugging CSS scroll using one simple style

I have been doing a lot of complicated front-end work off lately and that always brings me back to the class conundrum...

CSS :has a parent selector now

CSS now includes a :has selector that allows us to apply styles on the basis of what is happening inside an element....

How to fix “invalid active developer path” after MacOS update

If you are here, then you are getting an "invalid active developer path" error on running commands in the terminal after a...

Getting the value of an input element as a number without parseInt

Every once in a while, you come across something and you think, how did I not know this earlier? valueAsNumber is that thing...

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.