Horje
How to Sort a Dictionary by Value in JavaScript ?

In JavaScript, dictionaries do not have a built-in method to sort them by their values. However, there are several approaches to achieve this functionality.

Below are the possible Approaches:

Using Array.sort() with Object.entries()

In this approach first, we convert the dictionary into an array of key-value pairs using Object.entries() then we sort that array based on the values, and then we convert it back into a dictionary using Object.fromEntries().

Example: The below example uses Array.sort() with Object.entries() methods to sort a Dictionary by Value in JavaScript.

JavaScript
const dict = { 'AI': 91, 'ML': 75, 'DSA': 88, 'IOT': 85 };
const sortedDict = Object.fromEntries(
      Object.entries(dict).sort(([,a],[,b]) => a- b)
);
console.log(sortedDict);

Output
{ ML: 75, IOT: 85, DSA: 88, AI: 91 }

Using a custom sort function

In this approach, we are defining a custom sort function that sorts the dictionary based on their corresponding values. The custom function uses Object.keys() to get an array of keys and then sort the array based on the values. Finally, we will construct the dictionary using Array.reduce().

Example: The below example uses the Custom Sort Function to sort a Dictionary by Value in JavaScript.

JavaScript
function sortDictByValue(dict) {
  return Object.keys(dict)
    .sort((a, b) => dict[b] - dict[a])
    .reduce((acc, key) => {
      acc[key] = dict[key];
      return acc;
    }, {});
}

const dict = 
    { 'banana': 5, 'apple': 10, 'orange': 8, 'grape': 3 };
const sortedDict = sortDictByValue(dict);
console.log(sortedDict);

Output
{ apple: 10, orange: 8, banana: 5, grape: 3 }



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Edit a JavaScript Alert Box Title ? How to Edit a JavaScript Alert Box Title ?
JavaScript HTML DOM JavaScript HTML DOM
How to stop setInterval Call in JavaScript ? How to stop setInterval Call in JavaScript ?
JavaScript Program to Find Geometric mean in G.P. JavaScript Program to Find Geometric mean in G.P.
JavaScript Program to find nth term of Geometric Progression JavaScript Program to find nth term of Geometric Progression

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12