How to Sort ES6 Set in JavaScript

There is no direct method to sort an ES6 Set in JavaScript. However, there are few approaches available.

Here are two ways to sort an ES6 Set.

  1. Using Array.from(), Array.sort() and new Set()
  2. Using the Spread Operator and Sort() Method

Method 1: Using Array.from(), Array.sort() and new Set()

You can sort a Set by converting the Set into an Array using Array.from() method and then use the Array.sort() method to sort an array and then convert it back to the Set using the new Set() method.

const set = new Set([46, 21, 19]);
console.log(set);

let arr = [];
arr = Array.from(set)
arr.sort()
console.log(arr)

new_set = new Set(arr);
console.log(new_set)

Output

Set(3) { 46, 21, 19 }
[ 19, 21, 46 ]
Set(3) { 19, 21, 46 }

Method 2: Using the Spread Operator and Sort() Method

You can convert a Set to an Array using the Spread operator and apply the .sort() method on Array and convert it back to the Set.

const set = new Set([46, 21, 19]);
console.log(set);

let arr = [];
arr = [...set].sort()
arr.sort()
console.log(arr)

new_set = new Set(arr);
console.log(new_set)

Output

Set(3) { 46, 21, 19 }
[ 19, 21, 46 ]
Set(3) { 19, 21, 46 }

Related posts

TypeError: set.sort is not a function

Compare ES6 Sets for Equality