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

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

问题描述

这是我的字典:

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

我需要一种方式来排序我的 dict 字典从最小到最大,或从最大到最小。或者甚至会很好,我有一个数组与其中排序的键。但是我不知道如何使用 javascript 做这样的事情。在使用 python 之前,我已经完成了,如下所示:

  import heapq 
从运算符import itemgetter

30_largest = heapq.nlargest(8,dict.iteritems(),key = itemgetter(1))
pre>

我已经在谷歌搜索了,我发现数组有 sort()功能,但不是字典。所以我的问题是:如何排序字典按排序顺序获得前5个最大值?

解决方案

在JavaScript中可能不会很简单。

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

//创建项数组
var items = Object.keys(dict).map(function(key){
return [key,dict [key]];
});

//根据第二个元素排列数组
items.sort(function(first,second){
return second [1] - first [1];
});

//创建一个只有前5个项目的新数组
console.log(items.slice(0,5));
#[['d',17],['c',11],['z',9],['b',7],['y',6]]

创建项目数组的第一步类似于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的切片操作类似。

 打印项目[:5] 
#[['d',17],['c',11],['z' ],['b',7],['y',6]]


Here is my dictionary:

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

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))

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?

解决方案

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));
# [ [ 'd', 17 ], [ 'c', 11 ], [ 'z', 9 ], [ 'b', 7 ], [ 'y', 6 ] ]

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

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

which can be conveniently written as

items = list(dict.items())

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

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

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天全站免登陆