Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a dictionary by value in JavaScript

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?

like image 784
Michael Avatar asked Aug 26 '14 07:08

Michael


People also ask

Can you sort a dictionary in JavaScript?

Strictly speaking, you cannot sort a "dictionary" (JavaScript object), because JavaScript objects have no order. They are merely a "bag" of key/value pairs.

Can we sort dictionary values?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

How do you sort a value in JavaScript?

When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. Example: The sort function will sort 40 as a value lower than 100. When comparing 40 and 100, sort() calls the function(40,100).


2 Answers

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]] 
like image 66
thefourtheye Avatar answered Sep 18 '22 14:09

thefourtheye


The answer provided by @thefourtheye works to an extent, but it does not return the same "dictionary" structure.

If you want to return a sorted object with the same structure you started with, you can run this on the items returned from the accepted answer:

sorted_obj={} $.each(items, function(k, v) {     use_key = v[0]     use_value = v[1]     sorted_obj[use_key] = use_value }) 

Combine them for a single function that sorts a JavaScript object:

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

Example:

Simply pass your object into the sort_object function:

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

Result:

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

"Proof":

res = sort_object(dict)  $.each(res, function(elem, index) {     alert(elem) }) 
like image 29
Cybernetic Avatar answered Sep 18 '22 14:09

Cybernetic