javascript - Combining objects in an array with same key (date) -
i have array of objects , want combine objects have same date values have array like. looping through them .map(i => ) , chekcing on previous index i'm getting wrong values.
[{ id: '8', name: 'hfh', consumed_date: '2017-03-14', calories: 8952 }, { id: '7', name: 'onion', consumed_date: '2017-03-14', calories: 224}, { id: '6', name: 'onion', consumed_date: '2017-03-14', calories: 279}, { id: '2', name: 'ready-to-serve chocolate drink', consumed_date: '2017-01-01', calories: 3036} ]
and want end array like
[{date: 2017-03-14, calories: 9455}, date: 2017-01-01, calories: 3036}]
reduce
perfect situations this: need "loop" through items don't want straight-forward "a => modify(a)"-like behavior of map
, rather need reduce or collapse several values else (in case both input , output array of values reduced one).
we need variable hold state (the progress far) while loop through items. in more imperative style solved variable declared outside of for-loop, in reduce
"progress far"-variable (acc
) passed along each iteration, along next item.
const reducedarray = arr.reduce((acc, next) => { // acc stands accumulator const lastitemindex = acc.length -1; const acchascontent = acc.length >= 1; if(acchascontent && acc[lastitemindex].consumed_date == next.consumed_date) { acc[lastitemindex].calories += next.calories; } else { // first time seeing entry. add it! acc[lastitemindex +1] = next; } return acc; }, []); console.log(reducedarray)
(this solution assumes data sorted on date.)
Comments
Post a Comment