JavaScript — Sort a Set

Modern JavaScript comes with a built-in Set class. A set instance stores unique values of any type. You can use sets with primitive values and more complex data structures, like objects. A downside of sets in JavaScript is that they don’t provide the same methods as arrays. Sets don’t provide a sort function, you need to use a trick to sort a set.

This tutorial shows you how to sort a set in JavaScript.

JavaScript Series Overview

Sort a Set of Values in JavaScript

The trick to sorting a set of values in JavaScript is to convert the set to an array first and use the array’s sort function. The static Array.from method accepts an iterable and you can pass the set instance as an argument converting it to an array. From there you can use any array method, like Array#sort:

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

const sorted = Array.from(numbers).sort((a, b) => a - b)  

Please notice: if you need to proceed to work with the set because you need to ensure the uniqueness of items, you have to create a new set instance from the sorted array.

Another way to sort a set is using our open-source package @supercharge/set.

Use the @supercharge/set Package

I’m the maintainer of the @supercharge/set package providing an extended Set class. The Set class from the @supercharge/set package aligns with the Array class (and the one JavaScript should have shipped).

A supercharged Set instance provides a set.sort() method accepting a comparator that works the same way as in JavaScript:

import Set from '@supercharge/set'

Set.from([1, 1, 4, 2, 2, 5]).sort().toArray()  
// [1, 2, 3, 4, 5]

Set  
  .from([1, 1, 4, 2, 2, 5])
  .sort((a,b) => {
    return b - a
  })
  .toArray()
// [1, 2, 3, 4, 5]

Enjoy sorting JavaScript sets!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.