0

To sort an array in JavaScript, we can do like:

let myArr = [5,3,11,-1,-3,55,2,12,31,87,99];
myArr.sort((a,b) => a-b);
console.log(myArr);

but how do we sort a Set? for example if I have

let mySet = new Set();
for(let i=0; i<100; i++){
 mySet.add(Math.round(Math.random() * 50));
}

Is there any native function of the sort myArr.sort() which I can use to sort this set?

Hamid Ali
  • 29
  • 6
  • No. You'd have to convert it to an array, sort, convert it to a set again – adiga Dec 29 '20 at 11:17
  • @adiga Thanks, but it would, I guess, come with performance cost as it would be a twice copying, once either way, wouldn't it? – Hamid Ali Dec 29 '20 at 11:24
  • Instead of adding to the set directly, you can push to an array in the for loop. Sort the array and then create the set like `let mySet = new Set(sortedArray)` – adiga Dec 29 '20 at 11:40

0 Answers0