How to Sort a Set in JavaScript
A Set in JavaScript is a collection of unique values, but a key characteristic is that it maintains insertion order, not sorted order. This means that if you need to display or process the items in a Set in a sorted fashion (e.g., alphabetically or numerically), you must first convert it to an array, sort the array, and then optionally convert it back to a Set.
This guide will teach you the standard and most modern method for sorting a Set by converting it to an Array using the spread syntax (...). You will learn how to sort both strings and numbers correctly.
The Core Problem: Sets Are Not Self-Sorting
A Set is optimized for fast lookups and ensuring uniqueness. It remembers the order in which elements were added, but it does not have a built-in .sort() method like an Array.
Example of code with problems: the order is based on insertion but we want the order based on value!
// Problem: The order of this Set is based on insertion, not value.
const mySet = new Set();
mySet.add('cherry');
mySet.add('apple');
mySet.add('banana');
// Iterating over the Set gives the insertion order
for (const item of mySet) {
console.log(item);
}
Output:
cherry
apple
banana
To get a sorted result, we must use the sorting capabilities of an Array.
Solution: Convert to Array, Sort, and Convert Back
The process is a simple, three-step chain:
- Convert to Array: Use the spread syntax (
...) orArray.from()to create a new array from theSet. - Sort the Array: Use the
Array.prototype.sort()method on the new array. - Convert Back to
Set(Optional): If you need the final result to be aSet, pass the sorted array to thenew Set()constructor.
Sorting a Set of Strings (Alphabetical Sort)
When sorting an array of strings, the default behavior of sort() is alphabetical, which is exactly what we need.
Solution: this is the most concise and modern way to sort a Set of strings.
const mySet = new Set(['cherry', 'apple', 'banana']);
// 1. Convert to an array and sort it.
const sortedArray = [...mySet].sort();
console.log(sortedArray); // Output: ['apple', 'banana', 'cherry']
// 2. (Optional) Convert the sorted array back into a Set.
const sortedSet = new Set(sortedArray);
console.log(sortedSet); // Output: Set(3) { 'apple', 'banana', 'cherry' }
Output:
['apple', 'banana', 'cherry']
Set(3) {'apple', 'banana', 'cherry'}
You can also perform this in a single, chained line:
const sortedSet = new Set([...mySet].sort());
Sorting a Set of Numbers (Numerical Sort)
This is a critical case that often trips up beginners. The default sort() method converts elements to strings before comparing them. This leads to incorrect results for numbers.
Problem: Incorrect Sort
const numberSet = new Set([10, 2, 100]);
// WRONG: This sorts alphabetically ("10", "100", "2")
const incorrectlySorted = [...numberSet].sort();
console.log(incorrectlySorted);
Output: (This is NOT correct!)
[10, 100, 2]
The solution to sort numbers correctly is that you must provide a compare function to the sort() method. For ascending order, the function is (a, b) => a - b.
const numberSet = new Set([10, 2, 100]);
// CORRECT: Use a compare function for a numerical sort.
const sortedArray = [...numberSet].sort((a, b) => a - b);
console.log(sortedArray); // Output: [2, 10, 100]
// Optional: Convert back to a Set
const sortedSet = new Set(sortedArray);
console.log(sortedSet); // Output: Set(3) { 2, 10, 100 }
Output:
[2, 10, 100]
Set(3) {2, 10, 100}
Conclusion
While Set objects do not have a native .sort() method, they can be easily sorted by leveraging the power of Array.prototype.sort().
- The standard process is:
Set->Array->sort()->Set. - The most modern and concise way to convert a
Setto anArrayis with the spread syntax ([...mySet]). - For strings, a simple
.sort()is sufficient. - For numbers, you must provide a compare function to ensure a correct numerical sort:
.sort((a, b) => a - b).