I have an array of Objects that I need to reduce down based on a property and sum the other property. This solution is pretty much what I'm after , but I need to avoid using _.chain
as am importing only specific modules.
I've tried using flow, but am not getting any values:
const sumBy = require('lodash/fp/sumBy');
const flow = require('lodash/fp/flow');
const groupBy = require('lodash/fp/groupBy');
const map = require('lodash/fp/map');
const list = [
{ property: 'foo', value: 1 },
{ property: 'foo', value: 3 },
{ property: 'bar', value: 2 },
{ property: 'bar', value: 3 },
{ property: 'chu', value: 8 },
];
const foo = flow(
groupBy('property'),
map((objs, key) => {
return {
property: key,
value: sumBy(objs, 'value')
}
})
)(list)
This returns
[
{ property: undefined, value: 0 },
{ property: undefined, value: 0 },
{ property: undefined, value: 0 }
]
Ideally, I'd like to do this in vanilla es6, I've had a go at it, but not sure how to do the sum.
const bar = list.reduce((o, v) => {
return {...o, [v.property]: v.value}
}, {})
How about the following ES6 only solution:
const list = [ { property: 'foo', value: 1 }, { property: 'foo', value: 3 }, { property: 'bar', value: 2 }, { property: 'bar', value: 3 }, { property: 'chu', value: 8 }, ]; const result = list.reduce((obj, el) => { obj[el.property] = (obj[el.property] || 0) + el.value; return obj; }, {}); console.log(result);
You could take a Map
.
const list = [{ property: 'foo', value: 1 }, { property: 'foo', value: 3 }, { property: 'bar', value: 2 }, { property: 'bar', value: 3 }, { property: 'chu', value: 8 }], result = Array.from( list.reduce((m, { property, value }) => m.set(property, (m.get(property) || 0) + value), new Map), (([property, value]) => ({ property, value })) ); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
With lodash
const list = [{ property: 'foo', value: 1 }, { property: 'foo', value: 3 }, { property: 'bar', value: 2 }, { property: 'bar', value: 3 }, { property: 'chu', value: 8 }], result = _(list) .groupBy('property') .map((array, property) => ({ property, value: _.sumBy(array, 'value')})) ; console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
This could be thought of as a less efficient but nicer-to-read variant of the answer from Ruben Helsloot.
const sumValues = list => list .reduce ((obj, {property, value}) => ({ ... obj, [property]: (obj [property] || 0) + value }), {}) const list = [{property: 'foo', value: 1}, {property: 'foo', value: 3}, {property: 'bar', value: 2}, {property: 'bar', value: 3}, {property: 'chu', value: 8}] console .log (sumValues (list))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.