How can I sort an ES6 `Set`?

JavascriptArraysSortingSetEcmascript 6

Javascript Problem Overview


new Set(['b', 'a', 'c']).sort() throws TypeError: set.sort is not a function. How can I sort a Set to ensure a particular iteration order?

Javascript Solutions


Solution 1 - Javascript

A set is not an ordered abstract data structure.

A Set however always has the same iteration order - element insertion order [1], so when you iterate it (by an iterating method, by calling Symbol.iterator, or by a for.. of loop) you can always expect that.

You can always convert the set to an array and sort that.

Array.from(new Set(["b","a","c"])).sort();
[...(new Set(["b","a","c"]))].sort(); // with spread.

[1] forEach and CreateSetIterator

Solution 2 - Javascript

In some cases it may be preferable to "sort" the set in-place, similar to array.sort(), it can be done like this:

function sortSet(set) {
  const entries = [];
  for (const member of set) {
    entries.push(member);
  }
  set.clear();
  for (const entry of entries.sort()) {
    set.add(entry);
  }
  return set;
};

sortSet(new Set([3,2,1]))
// => Set(3) { 1, 2, 3 }

Solution 3 - Javascript

the simplest way to do it as.

console.log(new Set(['b', 'a', 'c'].sort()))
//Set(3) {"a", "b", "c"}

Solution 4 - Javascript

The .sort function is a higher order function which means it can have another function inside. First of all only .sort() may work with characters or strings but it will give bugs for numbers. I have discussed sets in my video along with sort function. I hope you understand it. https://www.youtube.com/watch?v=ztw4Gh8eogw

//This is sort() for getting numbers in ascending order:
const setC = new Set(([58,12,11,10,5,32]).sort((a,b)=>a -b));
//This is sort() for getting numbers in descending order:
const setC = new Set(([58,12,11,10,5,32]).sort((a,b)=>b -a));
//This is sort() for strings
const setD=new Set((['mangoes','bananas', 'apples','oranages']).sort());
// This is sort() for characters
const setD=new Set((['m', 'b', 'a', 'r']).sort());
You can convert the set to an array too and then sort it but that is not 
required in your case.
const arrayofsetA = Array.from(setA);
//for strings or characters
arrayofsetA.sort();
//for numbers or floating point numbers
arrayofsetA.sort((a,b) => a-b);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionericsocoView Question on Stackoverflow
Solution 1 - JavascriptBenjamin GruenbaumView Answer on Stackoverflow
Solution 2 - JavascriptsilverwindView Answer on Stackoverflow
Solution 3 - JavascriptTaimoor QureshiView Answer on Stackoverflow
Solution 4 - JavascriptSamanja CartagenaView Answer on Stackoverflow