Sort a set in JavaScript in Ascending or Descending order

In this tutorial, we will learn how to sort a set in JavaScript in Ascending or Descending order.

Sort a Javascript set in Ascending or Descending order

A Set is a data structure that is used to store unique values.

It remembers the order of the insertion of the values and there are often times when we want to sort the values.

To sort, we will have first to convert the set into an array and then use the Array.sort() to sort the array and then add these sorted values back to the set.

Convert set into an array

There are two ways in which we can convert a set into an array.

1. Using Array.from()

const set = new Set([3, 2, 1]);

const arrayFromSet = Array.from(set);

console.log(arrayFromSet);
// [3, 2, 1]

2. Using the spread operator (…)

const set = new Set([3, 2, 1]);

const arrayFromSet = [...set];

console.log(arrayFromSet);
// [3, 2, 1]

Now that we have the array of values it can be sorted.

Sorting Javascript set in ascending order

The Array.sort() method, sorts the values depending upon the return value of the callback function.

  • If the value is positive it will sort in ascending order.
  • If the value is negative it will be sorted in descending order.
  • If it is zero, it will do nothing.

By default, if the callback function is not passed, it will sort in ascending order.

const set = new Set([3, 2, 1]);

const arrayFromSet = Array.from(set);

const sortedArray = arrayFromSet.sort();

const sortedSet = new Set(sortedArray);

console.log([...sortedSet]);
//[1, 2, 3]

Sorting Javascript set in descending order

If we have a numeric value and we have to sort that in descending order, we will have to do the comparison in the callback function of the sort and return negative values.

This can be done by subtracting the next value from the current value.

const set = new Set([1, 2, 3]);

const arrayFromSet = Array.from(set);

// sort in descending order
const sortedArray = arrayFromSet.sort((a, b) => b - a);

const sortedSet = new Set(sortedArray);

console.log([...sortedSet]);
// [3, 2, 1]

Sorting a JavaScript set with string values

The string values will be sorted in ascending order by default but to sort them in descending order we will have to do the locale comparison of the strings.

const set = new Set(["one", "two", "three"]);

const arrayFromSet = Array.from(set);

// sort in descending order
const sortedArray = arrayFromSet.sort((a, b) => b.localeCompare(a));

const sortedSet = new Set(sortedArray);

console.log([...sortedSet]);
//["two","three","one"]

The logic of comparison is an individual’s choice and thus according to the requirement, it can be updated in the callback function of Array.sort().