gpt4 book ai didi

javascript - 在 JavaScript 中按值对字典进行排序

转载 作者:行者123 更新时间:2023-12-03 00:39:15 24 4
gpt4 key购买 nike

这是我的字典:

const dict = {
"x" : 1,
"y" : 6,
"z" : 9,
"a" : 5,
"b" : 7,
"c" : 11,
"d" : 17,
"t" : 3
};

我需要一种方法来对我的 dict 字典进行从最小到最大或从最大到最小的排序。或者即使我有一个包含排序键的数组也很好。但我不知道如何使用javascript来做这样的事情。我在使用python之前已经完成了,如下所示:

import heapq
from operator import itemgetter

thirty_largest = heapq.nlargest(8, dict.iteritems(), key=itemgetter(1))

我在Google上搜索过,发现数组有sort()函数,但字典没有。所以我的问题是:如何对字典进行排序按排序顺序获取前 5 个最大值?

最佳答案

在 JavaScript 中它可能并不简单。

var dict = {
"x": 1,
"y": 6,
"z": 9,
"a": 5,
"b": 7,
"c": 11,
"d": 17,
"t": 3
};

// Create items array
var items = Object.keys(dict).map(function(key) {
return [key, dict[key]];
});

// Sort the array based on the second element
items.sort(function(first, second) {
return second[1] - first[1];
});

// Create a new array with only the first 5 items
console.log(items.slice(0, 5));

第一步,创建 items 数组,类似于 Python 的

items = map(lambda x: [x, var[x]], var.keys())

可以方便地写为

items = list(dict.items())

排序步骤与Python使用cmp参数排序类似

items.sort(cmp=lambda x, y: y[1] - x[1])

最后一步类似于Python的切片操作。

print items[:5]
// [['d', 17], ['c', 11], ['z', 9], ['b', 7], ['y', 6]]

关于javascript - 在 JavaScript 中按值对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25500316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com