简答
new Map([...map].sort((a, b) =>
// Some sort function comparing keys with a[0] b[0] or values with a[1] b[1]
))
如果您期待字符串: 与.sort 一样,如果较低则需要返回 -1,如果相等则需要返回 0;对于字符串,the recommended way 正在使用 .localeCompare(),它可以正确执行此操作并自动处理像 ä 这样位置因用户区域而异的尴尬字符。
所以这里有一个简单的方法来通过字符串keys对地图进行排序:
new Map([...map].sort((a, b) => String(a[0]).localeCompare(b[0])))
...并通过字符串值:
new Map([...map].sort((a, b) => String(a[1]).localeCompare(b[1])))
这些是类型安全的,因为它们在遇到非字符串键或值时不会抛出错误。开头的String() 将a 强制为字符串(并且有利于可读性),.localeCompare() 本身将其参数强制为字符串而不会出现错误。
用例子详细说明
tldr:...map.entries() 是多余的,...map 就可以了;一个懒惰的.sort() 没有传递排序函数可能会导致字符串强制导致奇怪的边缘情况错误。
[...map.entries()] 中的 .entries()(在许多答案中建议)是多余的,可能会添加额外的地图迭代,除非 JS 引擎为您优化了它。
在简单的测试用例中,你可以按照问题的要求做:
new Map([...map].sort())
...如果键都是字符串,则比较压缩和强制逗号连接的键值字符串,如'2-1,foo' 和'0-1,[object Object]',返回具有新插入顺序的新 Map:
注意:如果您在 SO 的控制台输出中只看到 {},请查看您的真实浏览器控制台
const map = new Map([
['2-1', 'foo'],
['0-1', { bar: 'bar' }],
['3-5', () => 'fuz'],
['3-2', [ 'baz' ]]
])
console.log(new Map([...map].sort()))
但是,像这样依赖强制和字符串化并不是一个好习惯。您可以获得以下惊喜:
const map = new Map([
['2', '3,buh?'],
['2,1', 'foo'],
['0,1', { bar: 'bar' }],
['3,5', () => 'fuz'],
['3,2', [ 'baz' ]],
])
// Compares '2,3,buh?' with '2,1,foo'
// Therefore sorts ['2', '3,buh?'] ******AFTER****** ['2,1', 'foo']
console.log('Buh?', new Map([...map].sort()))
// Let's see exactly what each iteration is using as its comparator
for (const iteration of map) {
console.log(iteration.toString())
}
这样的错误真的很难调试 - 不要冒险!
如果要对键或值进行排序,最好在排序函数中使用a[0] 和b[0] 显式访问它们,如上所示;或在函数参数中使用数组解构:
const map = new Map([
['2,1', 'this is overwritten'],
['2,1', '0,1'],
['0,1', '2,1'],
['2,2', '3,5'],
['3,5', '2,1'],
['2', ',9,9']
])
// Examples using array destructuring. We're saying 'keys' and 'values'
// in the function names so it's clear and readable what the intent is.
const sortStringKeys = ([a], [b]) => String(a).localeCompare(b)
const sortStringValues = ([,a], [,b]) => String(a).localeCompare(b)
console.log('By keys:', new Map([...map].sort(sortStringKeys)))
console.log('By values:', new Map([...map].sort(sortStringValues)))
如果您需要与字符串的字母顺序不同的比较,请不要忘记始终确保返回 -1 和 1 之前和之后,而不是 false 或 0 与原始 @ 987654350@,因为这被视为平等。