我有字典
var unsorted = { "Bob":500, "James": 200, "Alex":750 }
我要创建一个像这样的列表:
var sorted = [["Alex",750],["Bob",500],["James",200]]
排序顺序是根据字典的值从高到低的顺序。
答案 0 :(得分:1)
我会这样:
const unsorted = { "Bob": 500, "James": 200, "Alex": 750 };
const sorted = Object.entries(unsorted) // object to array of arrays
.sort((a, b) => b[1] - a[1]); // sort descending by 2nd element of the arrays
console.log(sorted);
答案 1 :(得分:1)
可能是这个吗?
const unsorted = { "Bob":500, "James": 200, "Alex":750 }
const sorted = Object.keys(unsorted)
.sort((a,b)=>unsorted[b]-unsorted[a])
.map(e=>[e,unsorted[e]])
console.log( JSON.stringify(sorted) ) // [["Alex",750],["Bob",500],["James",200]]