根据对象创建重复的嵌套列表[重复]

问题描述 投票:-3回答:2
我有字典

var unsorted = { "Bob":500, "James": 200, "Alex":750 }

我想创建一个这样的列表:

var sorted = [["Alex",750],["Bob",500],["James",200]]

排序后的列表根据字典的值从高到低顺序排列。
javascript arrays javascript-objects
2个回答
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);

0
投票
可能是这个吗?

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]]
© www.soinside.com 2019 - 2024. All rights reserved.