Reputation: 547
I am using lodash library for my Node.JS project and I need to sort some tracks depending their tags given by users. So far, I am able to group by object_id the tracks, but not being able to sort them by the number of records for the same object_id
For example I have an array of objects as below:
{
"error": false,
"status": 200,
"data": [
{
"id": 1,
"object_id": 2,
"term_taxonomy_id": 1,
"user_id": 1,
},
{
"id": 3,
"object_id": 3,
"term_taxonomy_id": 1,
"user_id": 1,
},
{
"id": 10,
"object_id": 2,
"term_taxonomy_id": 1,
"user_id": 3,
},
{
"id": 12,
"object_id": 2,
"term_taxonomy_id": 1,
"user_id": 5,
},
{
"id": 14,
"object_id": 1,
"term_taxonomy_id": 1,
"user_id": 5,
},
{
"id": 15,
"object_id": 1,
"term_taxonomy_id": 1,
"user_id": 3,
}
]
}
Using lodash I want to have a result like this: [2,1,3] as the object_id of 2 is repeated three times (max from others) and should be top, and so on...
Any idea? Thanks
Upvotes: 2
Views: 1247
Reputation: 1975
_.chain(data)
.groupBy(function(d) { return d.object_id; })
.map(function(g) { return [g[0].object_id, g.length]; })
.sortBy(function(d) { return d[1] * -1; }) // d[1] is the length of each group
.map(function(d) { return d[0]; }) // d[0] is the gorup's key
.value();
Upvotes: 2