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?
4 Answers
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
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 } the simplest way to do it as.
console.log(new Set(['b', 'a', 'c'].sort())) //Set(3) {"a", "b", "c"} 1The .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.
//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);