Mic*_*ael 24 javascript sorting dictionary object
这是我的字典:
const dict = {
"x" : 1,
"y" : 6,
"z" : 9,
"a" : 5,
"b" : 7,
"c" : 11,
"d" : 17,
"t" : 3
};
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来将dict字典从最小到最大,或从最大到最小.或者甚至没问题我有一个带有排序键的数组.但我不知道如何使用这样的东西javascript.在使用之前我已经完成了python,像这样:
import heapq
from operator import itemgetter
thirty_largest = heapq.nlargest(8, dict.iteritems(), key=itemgetter(1))
Run Code Online (Sandbox Code Playgroud)
我在谷歌搜索过它,我发现数组有sort()功能但没有字典.所以我的问题是:我如何对字典进行排序或按排序顺序获得前5大值?
the*_*eye 48
它在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));Run Code Online (Sandbox Code Playgroud)
第一步,创建items数组,类似于Python
items = map(lambda x: [x, var[x]], var.keys())
Run Code Online (Sandbox Code Playgroud)
可以方便地写成
items = list(dict.items())
Run Code Online (Sandbox Code Playgroud)
排序步骤类似于Python的cmp参数排序
items.sort(cmp=lambda x, y: y[1] - x[1])
Run Code Online (Sandbox Code Playgroud)
最后一步类似于Python的切片操作.
print items[:5]
// [['d', 17], ['c', 11], ['z', 9], ['b', 7], ['y', 6]]
Run Code Online (Sandbox Code Playgroud)
首先,你可能称之为“字典”的东西在 JavaScript 中被称为“对象”。你的 'dict' 变量是一个对象。
JS 中的对象没有排序,因此无法对对象进行排序。幸运的是,数组是有序的;我们会将您的字典转换为数组。看看下面吧。
//dict -> a js object
var dict = {"x" : 1,
"y" : 6,
"z" : 9,
"a" : 5,
"b" : 7,
"c" : 11,
"d" : 17,
"t" : 3};
//Use the 'keys' function from the Object class to get the keys of your dictionary
//'keys' will be an array containing ["x", "y", "z"...]
var keys = Object.keys(dict);
//Get the number of keys - easy using the array 'length' property
var i, len = keys.length;
//Sort the keys. We can use the sort() method because 'keys' is an array
keys.sort();
//This array will hold your key/value pairs in an ordered way
//it will be an array of objects
var sortedDict = [];
//Now let's go throught your keys in the sorted order
for (i = 0; i < len; i++)
{
//get the current key
k = keys[i];
//show you the key and the value (retrieved by accessing dict with current key)
alert(k + ':' + dict[k]);
//Using the array 'push' method, we add an object at the end of the result array
//It will hold the key/value pair
sortedDict.push({'key': k, 'value':dict[k]});
}
//Result
console.log(sortedDict);
Run Code Online (Sandbox Code Playgroud)
你可以在这里尝试一下
如果您想更改排序,请查看此处
如果您想要前五个最大值,那么,使用 for 循环遍历sortedDict 5 次并获取这些值:
function getFiveFirstValues(){
var valuesArray = [];
for (i = 0; i < 5; i++)
{
valuesArray.push(sortedDict[i].value);
}
return valuesArray;
}
Run Code Online (Sandbox Code Playgroud)
请记住,在 JavaScript 中,对象是无序的。它们看起来可能是有序的,但实际上并非如此,并且根据浏览器的 JS 实现,它们的顺序可能会有所不同。
在此示例中,sortedDict 是一个数组(已排序),因此可以排序。在该数组的每个元素中,您将找到每对“字典”的 KEY 和 VALUE 对。
@thefourtheye 提供的答案在一定程度上有效,但它不会返回相同的“字典”结构。
如果你想返回一个与你开始的结构相同的排序对象,你可以在从接受的答案返回的项目上运行它:
sorted_obj={}
$.each(items, function(k, v) {
use_key = v[0]
use_value = v[1]
sorted_obj[use_key] = use_value
})
Run Code Online (Sandbox Code Playgroud)
将它们组合为一个对 JavaScript 对象进行排序的函数:
function sort_object(obj) {
items = Object.keys(obj).map(function(key) {
return [key, obj[key]];
});
items.sort(function(first, second) {
return second[1] - first[1];
});
sorted_obj={}
$.each(items, function(k, v) {
use_key = v[0]
use_value = v[1]
sorted_obj[use_key] = use_value
})
return(sorted_obj)
}
Run Code Online (Sandbox Code Playgroud)
例子:
只需将您的对象传递给 sort_object 函数:
dict = {
"x" : 1,
"y" : 6,
"z" : 9,
"a" : 5,
"b" : 7,
"c" : 11,
"d" : 17,
"t" : 3
};
sort_object(dict)
Run Code Online (Sandbox Code Playgroud)
结果:
{
"d":17,
"c":11,
"z":9,
"b":7,
"y":6,
"a":5,
"t":3,
"x":1
}
Run Code Online (Sandbox Code Playgroud)
“证明”:
res = sort_object(dict)
$.each(res, function(elem, index) {
alert(elem)
})
Run Code Online (Sandbox Code Playgroud)
您可以尝试以下代码。它按值排序整数数组。
function sortJsObject() {
var dict = {"x" : 1, "y" : 6, "z" : 9, "a" : 5, "b" : 7, "c" : 11, "d" : 17, "t" : 3};
var keys = [];
for(var key in dict) {
keys[keys.length] = key;
}
var values = [];
for(var i = 0; i < keys.length; i++) {
values[values.length] = dict[keys [i]];
}
var sortedValues = values.sort(sortNumber);
console.log(sortedValues);
}
// this is needed to sort values as integers
function sortNumber(a,b) {
return a - b;
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。