Sort a dictionary by value in JavaScript

JavascriptSortingObjectDictionary

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

You can try the following code. It gets sorted 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 it helps.

Solution 4 - Javascript

First things first, what you may call a 'dictionary' is called an 'Object' in JavaScript. Your 'dict' variable is an object.

Objects are not ordered in JS, so you cannot sort an object. Fortunately arrays are ordered; we will convert your dictionary to 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'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);

You can try it here

If you want to change the sorting, have a look here

If you want the first five biggest values, well, loop over sortedDict with a for loop 5 times and get those values out:

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

Please remember that in JavaScript, objects are UNORDERED. They may seem to be ordered, but they are not, and depending on the JS implementation of your browser their order can be different.

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

Solution 5 - 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.

If you want to find the n largest values in the object, then one way or another you need to convert the object into an array, whose elements are ordered, such as with @thefourtheye's solution. If you want to sort the keys, then well, sort them with Object.keys(object).sort() as another answer shows you how to.

Solution 6 - Javascript

This is a complete piece of code, according to previous answers and https://stackoverflow.com/questions/34913675/how-to-iterate-keys-values-in-javascript:

class DictUtils {
    static entries(dictionary) {

        try {

            //ECMAScript 2017 and higher, better performance if support
            return Object.entries(dictionary);

        } catch (error) {

            //ECMAScript 5 and higher, full compatible but lower performance
            return Object.keys(dictionary).map(function(key) {
                return [key, dictionary[key]];
            });
        }

    }
    
    static sort(dictionary, sort_function) {
        return DictUtils.entries(dictionary)
            .sort(sort_function)
            .reduce((sorted, kv)=>{
                sorted[kv[0]] = kv[1]; 
                return sorted;
            }, {});
    }

} 

class SortFunctions {
    static compare(o0, o1) {
        //TODO compelte for not-number values
        return o0 - o1;
    }
    static byValueDescending(kv0, kv1) {
        return SortFunctions.compare(kv1[1], kv0[1]);
    }
    static byValueAscending(kv0, kv1) {
        return SortFunctions.compare(kv0[1], kv1[1]);
    }

}

let dict = {
    "jack": 10,
    "joe": 20,
    "nick": 8,
    "sare": 12
}

let sorted = DictUtils.sort(dict, SortFunctions.byValueDescending)

console.log(sorted);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - JavascriptthefourtheyeView Answer on Stackoverflow
Solution 2 - JavascriptCyberneticView Answer on Stackoverflow
Solution 3 - JavascriptAturView Answer on Stackoverflow
Solution 4 - JavascriptRayjaxView Answer on Stackoverflow
Solution 5 - Javascriptuser663031View Answer on Stackoverflow
Solution 6 - JavascriptMostafa NazariView Answer on Stackoverflow