Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  42] [ 1]  / answers: 1 / hits: 121246  / 10 Years ago, tue, august 26, 2014, 12:00:00

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?


More From » sorting

 Answers
20

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





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

[#69661] Friday, August 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;