Sort 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 a dict dictionary from smallest to maximum or from maximum to smallest. Or it would even be nice, I had an array with sorted keys in it. But I do not know how to do this using javascript . I did this before using python , for example:

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

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

+16
source share
5 answers

It may not be so simple 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 an array of elements, is similar to Python

 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 sorting Python with the cmp parameter

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

and the last step is like a Python slicing operation.

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

You can try the following code. It sorts an integer array by value.

jsFiddle link

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

Hope this helps.

+4
source

First of all, what you can call a "dictionary" is called "Object" in JavaScript. Your variable 'dict' is an object.

Objects are not ordered in JS, so you cannot sort an object. Fortunately, arrays are ordered ; we will convert your dictionary into an array. Just take a look below.

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

You can try here

If you want to change the sorting , look here.

If you need the first five largest values , well, loop on sortedDict with a for loop 5 times and get these values:

 function getFiveFirstValues(){ var valuesArray = []; for (i = 0; i < 5; i++) { valuesArray.push(sortedDict[i].value); } return valuesArray; } 

Remember that JavaScript objects are UNORDERED. They may seem orderly , but they are not, and depending on your browser's JS implementation, their order may be different.

In this example, sortedDict is an array (which is ordered) and therefore can be sorted. In each element of this array, you will find a pair of KEY and VALUE for each pair of your dictionary.

+2
source

Strictly speaking, you cannot sort a dictionary (a JavaScript object) because JavaScript objects are out of order. They are just a β€œbag” of key / value pairs.

If you want to find the n largest values ​​in an object, then somehow you need to convert the object to an array whose elements are ordered, for example, with the @thefourtheye solution. If you want to sort keys, then fine, sort them with Object.keys(object).sort() , as another answer shows how to do this.

+1
source

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

If you want to return a sorted object with the same structure with which you started , you can do this for elements 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 one 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) } 

An example :

Just pass your object to 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) }) 
+1
source

Source: https://habr.com/ru/post/974345/


All Articles