Advertisements

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.

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}
JavaScript

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'}
JavaScript

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.

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria

Recent Posts

Remapping keyboard keys to avoid Carpal Tunnel

I am terrible at optimizing my keyboard layout for anything. But off lately, my little…

1 week ago

Fixing cookies are blocked for a website with shields down on Brave

I recently switched completely to the Brave browser and have set ad blocking to aggressive…

4 months ago

Generating a QR code using Node.js

I was preparing a slide deck for a hackathon and decided to put in a…

5 months ago

How to clear the global npx cache

I have been using npx a lot lately, especially whenever I want to use a…

6 months ago

Copy/Pasting output from the terminal

Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…

6 months ago

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

7 months ago
Advertisements