How to use Object.entries method In Javascript
In this approach, we will first convert the associative array into an array of key-value pairs using Object.entries. This will generate array of arrays in which sub-array contains a key-value pair. Then we will sort the array such that it sorts the array in ascending order based on the second element of each sub-array. Then use reduce function to convert the sorted array back into an object.
Example: This example shows the use of the above-explained approach.
const a = {
a: 90,
e: 12,
o: 27,
};
const arr = Object.entries(a);
arr.sort((a, b) => a[1] - b[1]);
const res = arr.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
console.log(res)
Output
{ e: 12, o: 27, a: 90 }
JavaScript Program to Sort an Associative Array by its Values
In Javascript, “arrays” are indexed by numerical values, while “objects” are essentially what you might refer to as associative arrays. It’s important to note that “objects” do not have a guaranteed order. In this article, we will learn how can we sort an associative array by its values.
Table of Content
- Using sort() method
- Using Object.entries method
- Using object.key method
- Using Object.keys() and Array.map()