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.

JavaScript
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()

Similar Reads

Using sort() method

In this approach, we create a sorting function that has its own comparator which basically sorts the array based on the value property that we provide to it. This will help to achieve the sorting on the array we defined by making little changes in the structure....

Using Object.entries method

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....

Using object.key method

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....

Using Object.keys() and Array.map()

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....