How to pick latest item per user from an array in Javascript?
For example, I have an array like this:
[
{
"data": "some data",
"user": "A",
"createdAt":"2016-12-24",
},
{
"data": "some data2",
"user": "B",
"createdAt":"2016-12-24",
},
{
"data": "some data3",
"user": "A",
"createdAt":"2016-12-25",
},
{
"data": "some data4",
"user": "A",
"createdAt":"2016-12-23",
},
{
"data": "some data5",
"user": "B",
"createdAt":"2016-12-25",
},
{
"data": "some data6",
"user": "C",
"createdAt":"2016-12-24",
},
]
I only need the latest created item per one user, so I need an array like this:
[
{
"data": "some data3",
"user": "A",
"createdAt":"2016-12-25",
},
{
"data": "some data5",
"user": "B",
"createdAt":"2016-12-25",
},
{
"data": "some data6",
"user": "C",
"createdAt":"2016-12-24",
},
]
How can I do it with underscore or lodash?
Answer :
The key is to order by
user
then by createdAt
in descending order. Since createdAt
is a Date
it needs to be treated as such. Conveiniently, the orderBy
method allows one to specify either the property to order by or a function to evaluate (which returns the object to order by, in this case Date
).
Below's what I came up with:
var data = [{ ... }],
sorted = _.orderBy(
data,
['user', function(d) {
return new Date(d.createdAt)
}],
['asc', 'desc'] // 'desc' orders by date descending
),
uniqued = _.uniqBy(sorted, 'user');
source: http://stackoverflow.com/questions/41310265/how-to-pick-latest-item-per-user-from-an-array#41310442
COMMENTS