在 JavaScript 中按值对字典进行排序 [英] Sort a dictionary by value in JavaScript

查看:202
本文介绍了在 JavaScript 中按值对字典进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的字典:

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

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

I need a way to sort my dict dictionary from the least to the greatest or from the greatest to the least. Or even it would be fine I had an array with the sorted keys in it. But I do not know how to do such thing using javascript. I have done it before using python, like this:

import heapq
from operator import itemgetter

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

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

I have searched for it in Google and I found that arrays have sort() function but not dictionaries. So my question is: How can I sort the dictionary or get top 5 biggest values in sort order?

推荐答案

它在 JavaScript 中可能不是直截了当的.

It may not be straight forward in 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的

The first step, creating items array, is similar to Python's

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

可以方便地写成

items = list(dict.items())

并且排序步骤类似于Python的带有cmp参数的排序

and the sorting step is similar to Python's sorting with cmp parameter

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

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

and the last step is similar to the Python's slicing operation.

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

这篇关于在 JavaScript 中按值对字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆