Input:
const data = [
{
id: 'RS11',
name: 'Road 1',
quantity: {
lengthVal: 50
}
},
{
id: 'RS11',
name: 'Road 1',
quantity: {
lengthVal: 100
}
},
{
id: 'RS11',
name: 'Road 2',
quantity: {
lengthVal: 20
}
}
]
Each property, except quantity
, should be grouped. quantity.lengthVal
should be summarized. You should also add a property count
.
Expected Result:
const expected = [
{
id: 'RS11',
name: 'Road 1',
count: 2,
summarizedLength: 150
},
{
id: 'RS11',
name: 'Road 2',
count: 1,
summarizedLength: 20
}
]
This is what I tried:
const groupAndSum = (arr) => {
return _.chain(arr)
.groupBy((obj) => {
// Some reduce here?
return _.values(_.without(obj), 'quantity').join('|')
})
.map((val) => {
val[0].count = val.length;
delete val[0].quantity;
return val[0];
})
.value();
}
Jsbin: https://jsbin.com/totujopume/edit?html,js,console
The data set is quite large, so performance is important.
source
share