Asked  4 Months ago    Answers:  5   Viewed   1.1k times

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?

 Answers

98

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]]
Saturday, July 3, 2021
 
Wilk
answered 4 Months ago
36

You need to take advantage of the fact that the values are numbers.

>>> [v[0] for v in sorted(d.iteritems(), key=lambda(k, v): (-v, k))]
['peach', 'banana', 'beetroot', 'almond', 'apple']
Wednesday, June 2, 2021
 
inieto
answered 5 Months ago
13

As @epascarello mentions, there is no native sort function for objects in JavaScript.

If you are interested in sorting an array of your object's keys according to some order, you can use Object.keys()!

var buttons = {
  confirm: { value: 'foo', order: 0 },
  cancel: { value: 'bar', order: 2},
  delete: { value: 'baz', order: 1}
};

var sortedButtons = Object.keys(buttons).sort( function(keyA, keyB) {
  return buttons[keyA].order - buttons[keyB].order;
}); // returns ['confirm', 'delete', 'cancel']
Saturday, August 28, 2021
 
Bharanikumar
answered 2 Months ago
52

Yo could take a different approach and change Symbol.iterator of Map.prototype[@@iterator]() for a custom sorted result.

var map = new Map();

map.set("orange", 10);
map.set("apple", 5);
map.set("banana", 20);
map.set("cherry", 13);

map[Symbol.iterator] = function* () {
    yield* [...this.entries()].sort((a, b) => a[1] - b[1]);
}

for (let [key, value] of map) {     // get data sorted
    console.log(key + ' ' + value);
}

console.log([...map]);              // sorted order
console.log([...map.entries()]);    // original insertation order
.as-console-wrapper { max-height: 100% !important; top: 0; }
Saturday, September 4, 2021
 
Anton Barinov
answered 2 Months ago
91

(Answering own question)

Yes, its possible to use a dictionary of objects/classes in VBScript. The following is an example for those interested:

Class employeeclass
    Public first, last, salary
End Class
Dim employeedict: Set employeedict = CreateObject("Scripting.Dictionary")

Dim employee: Set employee = new employeeclass
With employee
    .first = "John"
    .last = "Doe"
    .salary = 50000
End With
employeedict.Add "1", employee

Set employee = new employeeclass
With employee
    .first = "Mary"
    .last = "Jane"
    .salary = 50000
End With
employeedict.Add "3", employee

Dim employeedetails: Set employeedetails = employeedict.Item("1")
WScript.StdOut.WriteLine("Name:" & employeedetails.first & " " & employeedetails.last & " $" & employeedetails.salary )
WScript.StdOut.WriteLine(employeedict.Item("3").first & " " & employeedict.Item("3").last & " makes $" & employeedict.Item("3").salary)

Prints out:

Name:John Doe $50000 
Mary Jane makes $50000
Friday, September 24, 2021
 
nomie
answered 3 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :