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.
- Using Array.from(), Array.sort() and new Set()
- 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

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.