How to use Object.keys() and Array.map() In Javascript
Using Object.keys() to extract keys, then Array.map() to create an array of key-value pairs. Sort this array by values. Finally, Array.reduce() converts it back to an object.
Example: In this example the function sortObjectByValues sorts an object’s entries by their values in ascending order.
function sortObjectByValues(obj) {
return Object.keys(obj)
.map(key => [key, obj[key]])
.sort((a, b) => a[1] - b[1])
.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
}
let obj = { a: 3, b: 1, c: 2 };
console.log(sortObjectByValues(obj));
Output
{ b: 1, c: 2, a: 3 }
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()