Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash orderBy based on property child count

I would like to count objects of property and orderBy considering the count result.

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

// Sort by `user` in ascending order and by `age` in descending order.
        _.orderBy(users, ['user', 'age'], ['asc', 'desc']);

From the doc, this work but what I want is to have something like :

var users = [
            { 'user': 'barney', 'age': 34 ,Likes: [{objAA},{objBA}]},
            { 'user': 'fred',   'age': 48 ,Likes: [{objBA},{objBB},{objBC}]},
            { 'user': 'barney', 'age': 34 ,Likes: [{objDA},{objDA}]},
            { 'user': 'barney', 'age': 34 ,Likes: [{objCA}]}
        ];

orderBy Likes count

var users = [
            { 'user': 'fred',   'age': 48 ,Likes: [{objBA},{objBB},{objBC}]},
            { 'user': 'barney', 'age': 34 ,Likes: [{objAA},{objBA}]},
            { 'user': 'barney', 'age': 34 ,Likes: [{objDA},{objDA}]},
            { 'user': 'barney', 'age': 34 ,Likes: [{objCA}]}
        ];

Is this possible using loadh only ?

What I need is something like

_.orderBy(users, ['user.Likes.length'], ['desc']);
_.orderBy(users, ['user.Likes'], ['desc']);

But above code doesn't work but no errors

I would like to use orderBy function to be able after to combine the ordering like

_.orderBy(users, ['user.Likes','user', 'age'], ['desc','asc', 'desc']);
like image 510
Aaleks Avatar asked Dec 18 '22 18:12

Aaleks


1 Answers

you may use function iterators like this

 _.orderBy(users, ['user', function (o) {
    return o.likes.length;
 }], ["asc", "asc"])

here's an example

var users = [{
  'user': 'fred',
  'age': 48,
  'likes': [{c:1}, {c:2}, {c:3}]
}, {
  'user': 'barney',
  'age': 34,
  'likes': [{c:1}, {c:2}, {c:3}, {c:3}]
}, {
  'user': 'ammar',
  'age': 25,
  'likes': [{c:1}, {c:2}, {c:3}, {c:3}, {c:1}, {c:2}, {c:3}]
}, {
  'user': 'boston',
  'age': 34,
  'likes': [{c:1}, {c:3}]
}, {
  'user': 'obama',
  'age': 34,
  'likes': [{c:1}]
}, {
  'user': 'barney',
  'age': 34,
  'likes': [{c:1}, {c:2}, {c:3}]
}];


document.write(JSON.stringify(_.orderBy(users, ['user', function (o) {
  return o.likes.length;
}], ["asc", "asc"]), null, 4))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script>
like image 68
Ammar Hasan Avatar answered Jan 02 '23 16:01

Ammar Hasan