How to use object.key method In Javascript
In this approach, we will first convert the associative array into an array of keys using Object.keys. This will generate array of keys. Then we will sort the 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 arr = {
b: 3,
a: 1,
d: 2,
};
const keys = Object.keys(arr);
const sarr = keys.sort((a, b) => arr[a] - arr[b]);
const obj = sarr.reduce((acc, key) => {
acc[key] = arr[key];
return acc;
}, {});
console.log(obj);
Output
{ a: 1, d: 2, b: 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()