How to sort objects by value

Let's say you have the following object in JS:

let obj = {a: 24, b: 12, c:21; d:15};

      

How can "obj" be converted to an array of object keys sorted by value?

+3


source to share


3 answers


let obj = {a: 24, b: 12, c:21, d:15};

// Get an array of the keys:
let keys = Object.keys(obj);

// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] - obj[b] });

console.log(keys);
      

Run codeHide result




Note that the above can be done in one line if desired with Object.keys(obj).sort(...)

. The simple .sort()

comparator function shown will only work for numeric values ​​(swap a

and b

for sorting in the opposite direction), but since in this question I am assuming this is fine ...

+5


source


var obj  = {
  a: 24, b: 12, c:21, d:15
};
var sortable = [];
for (var x in obj ) {
    sortable.push([x, obj[x]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

console.log(sortable)

      



+1


source


here is a way to get sorted object and get sorted object in reverse order

let sortedObject = {}
sortedObject = Object.keys(yourObject).sort((a, b) => {
                        return yourObject[a] - yourObject[b] 
                    }).reduce((prev, curr, i) => {
                        prev[i] = yourObject[curr]
                        return prev
                    }, {});

      

you can customize your sorting function as per your requirement

0


source







All Articles