I'm trying to group objects in an array by date:
var list = [
{
date: "2017-01-01",
type: "type1",
amount: 100
},
{
date: "2017-01-01",
type: "type2",
amount: 150
},
{
date: "2017-01-02",
type: "type1",
amount: 200
}
]
And I'm trying to get something like:
var dateArr = [
{
date: "2017-01-01",
activities: [
{
type: "type1",
amount: 100
},
{
type: "type2",
amount: 150
}]
}
]
I have tried a few things...like this using underscore (from here https://stackoverflow.com/a/15888912/4989305):
var dateArr = _
.chain(list)
.groupBy('date')
.map(function(value, key) {
return {
date: key,
activities: [{
type: _.pluck(value, 'type'),
amount: _.pluck(value, 'amount')
}]
}
})
.value();
I've also tried this (from here https://stackoverflow.com/a/31373860/4989305)
var dateArr = {};
list.forEach(function(item){
dateArr[item.date] = dateArr[item.date]||[];
dateArr[item.date].push(item);
});
But, for some reason both return empty.
Any help will be greatly appreciated.
You could use a hash table for groupiung by date and assign the single group to the result array.
I hope this is what you exactly need.
A few lines of modern JavaScript will get you the result you want:
Explaination:
Array.reduce
to consolidate the list into a set of results, a plain object, grouped by date.reduce
, so that the next item will consolidate into the same set.Object.values
to extract the values from the set. (Drop the keys)