Skip to content Skip to sidebar Skip to footer

Lodash - Sort Objects In Object ( Desc And Asc)

How to sort object of objects asc and desc using Lodash? For example i want to sort it by 'r' or 'd'. This is how my object looks like:

Solution 1:

Place internal objects in array and use function sortBy()

var users = [
 { 'user': 'fred',   'age': 48 },
 { 'user': 'barney', 'age': 36 },
 { 'user': 'fred',   'age': 40 },
 { 'user': 'barney', 'age': 34 }
];

_.sortBy(users, function(o) { return o.user; });
// → objects for[['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
console.log(users.reverse()); // desc order

Solution 2:

Pure JS is also very simple and you may do something like this;

var   obj = {a:16, b:2, c:8, d:4, e:1},
    okeys = Object.keys(obj),
   sorted = {};
okeys.sort((p,c) => obj[p] <= obj[c]).forEach((p,i) => sorted[okeys[i]] = obj[p]);
document.write('<pre> ' + JSON.stringify(sorted, 0, 2) + '</pre>');

I am sorting object properties according to their numerical values. Their values could be objects and you could sort according to these objects property values as well. But i can not comment on what could be a sensible reason behind doing all this.

Post a Comment for "Lodash - Sort Objects In Object ( Desc And Asc)"