How can I sort an ES6 `Set`?

前端 未结 1 1672
遇见更好的自我
遇见更好的自我 2020-12-14 05:26

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

相关标签:
1条回答
  • 2020-12-14 05:44

    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

    0 讨论(0)
提交回复
热议问题