The Set
object lets you store unique values of any type, whether primitive values or object references.
To sort a Set by value:
- Get an array of the Set’s entries using the spread syntax (
...
) or usingArray.from
- Call the
sort()
method on the array - Pass the result to the
Set()
constructor
Examples
Sort a Set with primitive values (numbers)
// 1- Create a Set object and append values to it
const mySet1 = new Set()
mySet1.add(1)
mySet1.add(5)
mySet1.add(4)
mySet1.add(3)
mySet1.add(2)
// 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);
console.log(sortedSet)
// 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 arrayarrayToSort
. - 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 ofa-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
.
- Note at this step, we’ve passed an arrow function
- In step4, we’ve assigned the results of the sorted array
arrayToSort
into a new Set objectsortedSet
, 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);
console.log(sortedSet);
// 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();
setOfCharacters.add('a')
setOfCharacters.add('d')
setOfCharacters.add('c')
setOfCharacters.add('z')
setOfCharacters.add('A')
console.log(setOfCharacters)
// Output: Set { 'a', 'd', 'c', 'z', 'A' }
const arrayToSort = Array.from(setOfCharacters).sort((a,b) => a > b ? 1: -1);
console.log(arrayToSort)
// Output: [ 'A', 'a', 'c', 'd', 'z' ]
const sortedSetOfCharacters = new Set(arrayToSort)
console.log(sortedSetOfCharacters)
// 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})
console.log(setOfObjects)
// Output: Set { { key: 1 }, { key: 4 }, { key: 2 }, { key: 3 } }
const arrayToSort = Array.from(setOfObjects).sort((objA, objB) => objA.key - objB.key);
console.log(arrayToSort)
// Output: [ { key: 1 }, { key: 2 }, { key: 3 }, { key: 4 } ]
const sortedSetOfObjects = new Set(arrayToSort)
console.log(sortedSetOfObjects)
// 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])
console.log(setOfArrays)
// Output: Set {[ 'top', 10 ],[ 'left', 30 ],[ 'right', 20 ],[ 'bottom', 25 ] }
const arrayToSort = Array.from(setOfArrays).sort((arrA, arrB) => arrA[1] - arrB[1]);
console.log(arrayToSort)
// Output: Set {[ 'top', 10 ][ 'right', 20 ],[ 'bottom', 25 ],[ 'left', 30 ] ] }
const sortedSetOfArrays = new Set(arrayToSort)
console.log(sortedSetOfArrays)
// 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