The title might seem quite verbose, but in reference to this answer posted in this question: https://stackoverflow.com/a/37623524/4111415
I was wondering what the let count = prev.get(curr.key) || 0;
actually meant. As far as I am aware the accumulator (prev
) is just a number; what is the get
method actually doing here? I have looked at the MDN documenation to no avail: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
let objArr = [
{key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
{key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
{key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
{key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
];
// first, convert data into a Map with reduce
let counts = objArr.reduce((prev, curr) => {
let count = prev.get(curr.key) || 0;
prev.set(curr.key, curr.val + count);
return prev;
}, new Map());
// then, map your counts object back to an array
let reducedObjArr = [...counts].map(([key, value]) => {
return {key, value}
})
console.log(reducedObjArr);