How can we sort a dictionary by value in JavaScript?

A dictionary in Javascript is a data structure that stores values as a key-value pair and is used for easy lookups. The stored values are also called associative arrays, as each entry into the dictionary is a key with an associated value.

Retrieving data

There are two ways to get data from a dictionary:

  • Object.keys(dictionary): Returns a list of keys from the dictionary.
  • Object.values(dictionary): Returns a list of values from the dictionary.
var dict = {
"Alice": 25, "Bob": 22, "James": 15, "Jenifer": 29,
"Sarah": 30, "Lukah": 18, "Steve": 41
};
// Printing the Keys of dict object
console.log("Keys in dict Object : ", Object.keys(dict));
// Printing the Values of dict object
console.log("Values in dict Object: ", Object.values(dict));

Sorting the dictionary by values

There are three steps involved in sorting the dictionary by values:

  1. We can convert the dictionary into an array of key-value pairs.
  2. We can sort the list by value.
  3. We can obtain the keys in the sorted order of the values.
var dict = {
"Alice": 25, "Bob": 22, "James": 15, "Jennifer": 29,
"Sarah": 30, "Luke": 18, "Steve": 41
};
// Step - 1
// Create the array of key-value pairs
var items = Object.keys(dict).map(
(key) => { return [key, dict[key]] });
// Step - 2
// Sort the array based on the second element (i.e. the value)
items.sort(
(first, second) => { return first[1] - second[1] }
);
// Step - 3
// Obtain the list of keys in sorted order of the values.
var keys = items.map(
(e) => { return e[0] });
console.log(keys);

Step 1

Convert the dictionary into an array of key-value pairs. This process uses the map function to get the items from the dict.

// Step - 1
// Create the array of key-value pairs
var items = Object.keys(dict).map(
(key) => { return [key, dict[key]] });

Step 2

Sort the array with a custom sort function using the second element of the list which is on index 1.

// Step - 2
// Sort the array based on the second element (i.e. the value)
items.sort(
(first, second) => { return first[1] - second[1] }
);

Step 3

Obtain the list of keys in the same order as the sorted values.

// Step - 3
// Obtain the list of keys in the same order as the sorted values
var keys = items.map(
(e) => { return e[0] });

Credits

This technique is usually known as the Schwartzian transform. It was first used by Randal Schwartz in 1994, and makes use of the decorate-sort-undecorate idiom.

Schwartz gave the following code to answer a query that asked for a way to sort a list of lines by their last word:

#!/usr/bin/perl
require 5; # New features, new bugs!
print
map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
map { [$_, /(\S+)$/] }
<>;

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved