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

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…

4 days ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

2 weeks ago

Node.js 20.6 adds built-in support for .env files

Node.js 20.6 added built-in support for the .env file. This is an excellent addition to the platform…

3 weeks ago

Object destructuring in TypeScript

Object destructuring is a powerful ES 6 feature that can help developers write cleaner code.…

1 month ago

Improve git clone performance in a CI pipeline

Have you felt particularly annoyed by the time it takes to clone a large repository,…

1 month ago

Fix: Hydration failed because the initial UI does not match what was rendered on the server

Within a React or Next.js app, if you encounter the error "Hydration failed because the…

2 months ago
Advertisements