How to sort Javascript Set by value

The Set object lets you store unique values of any type, whether primitive values or object references.

To sort a Set by value:

  1. Get an array of the Set’s entries using the spread syntax (...) or using Array.from
  2. Call the sort() method on the array
  3. Pass the result to the Set() constructor


Sort a Set with primitive values (numbers)

// 1- Create a Set object and append values to it
const mySet1 = new Set()

// 2- Fill the Set values into an array
const arrayToSort = Array.from(mySet1)
// 3- Sort the array using Array.sort function
arrayToSort.sort((a,b) => a-b)

// 4- Re-fill the sorted array into a new Set object
const sortedSet = new Set(arrayToSort);

// Expected output 
// Set(5) {1, 2, 3, 4, 5}

In the above example, we’ve done the following:

  • Created mySet1 object and append values to it.
  • Filled the mySet1 into an array arrayToSort.
  • Executed the Array.sort function over the array.
    • Note at this step, we’ve passed an arrow function (a,b) => a-b which is known as compare function, this function will compare the values of the array, and based on the result of a-b, the array values will be sorted in ascending order. In case we want to sort the array in descending order we simply can flip the compare function expression to (a,b) => a-b.
  • In step4, we’ve assigned the results of the sorted array arrayToSort into a new Set object sortedSet, and as shown in the logs, we’ve got the Set primitive values sorted in ascending order.
To sort in descending order:

We simply need to flip the compare function expression as the following:

arrayToSort.sort((a,b) => b-a);
const sortedSet = new Set(arrayToSort);

// Expected output
// Set(5) {5, 4, 3, 2, 1}

Note:  The default sort order is ascending, and if the compare function isn’t provided (i.e: we call the sort() without specifying the compare function) the elements will be converted to strings, then sorted according to each character’s Unicode code point value (UTF-16).

Sort a Set of characters

const setOfCharacters = new Set();

// Output: Set { 'a', 'd', 'c', 'z', 'A' }

const arrayToSort = Array.from(setOfCharacters).sort((a,b) => a > b ? 1: -1);
// Output: [ 'A', 'a', 'c', 'd', 'z' ]

const sortedSetOfCharacters = new Set(arrayToSort)
// Output: Set { 'A', 'a', 'c', 'd', 'z' }

A capital letter "A" is not equal to the lowercase "a". Which one is greater? The lowercase "a". Why? Because the lowercase character has a greater index in the internal encoding table JavaScript uses (Unicode).

To confirm we can use charCodeAt function to get the character code, see example below:

console.log("A:","A".charCodeAt(0), "| a:","a".charCodeAt(0),"| c:", "c".charCodeAt(0), "| d:","d".charCodeAt(0), "| z:","z".charCodeAt(0))

// Expected output: 
// A: 65 | a: 97 | c: 99 | d: 100 | z: 122

Sort a Set of objects

const setOfObjects = new Set();

setOfObjects.add({key: 1})
setOfObjects.add({key: 4})
setOfObjects.add({key: 2})
setOfObjects.add({key: 3})
// Output: Set { { key: 1 }, { key: 4 }, { key: 2 }, { key: 3 } }

const arrayToSort = Array.from(setOfObjects).sort((objA, objB) => objA.key - objB.key);
// Output: [ { key: 1 }, { key: 2 }, { key: 3 }, { key: 4 } ]

const sortedSetOfObjects = new Set(arrayToSort)
// Output: Set { { key: 1 }, { key: 2 }, { key: 3 }, { key: 4 } }

The difference here from the first example is that we are sorting objects by their values. And this difference appears on the Array.sort() compare function:

sort((objA, objB) => objA.key - objB.key)

In this compare function, we’re accepting two objects objA, objB, then we do the comparison by accessing the object key value.

Sort a Set of arrays

const setOfArrays = new Set();

setOfArrays.add(['top', 10])
setOfArrays.add(['left', 30])
setOfArrays.add(['right', 20])
setOfArrays.add(['bottom', 25])
// Output: Set {[ 'top', 10 ],[ 'left', 30 ],[ 'right', 20 ],[ 'bottom', 25 ] }

const arrayToSort = Array.from(setOfArrays).sort((arrA, arrB) => arrA[1] - arrB[1]);
// Output: Set {[ 'top', 10 ][ 'right', 20 ],[ 'bottom', 25 ],[ 'left', 30 ] ] }

const sortedSetOfArrays = new Set(arrayToSort)
// Output: Set {[ 'top', 10 ],[ 'right', 20 ],[ 'bottom', 25 ],[ 'left', 30 ] }

Same as the previous example, the difference here is that we are sorting a Set of arrays, and this appears in the compare function (arrA, arrB) => arrA[1] - arrB[1], the comparison operation happens by comparing the first array arrA element at index 1, with arrB element at index 1.

That’s it for How to sort Javascript Set by value.

And as always happy coding!

Photo from unslpash

Related Posts

How to remove credits link

How to remove credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: