So I have this array of objects which I need to reduce based on each object's prop value as well as count the total.
What I mean to say is, suppose I have this array of objects:
[
{ dateTime: '2021-07-30', count: 4 },
{ dateTime: '2021-07-31', count: 1 },
{ dateTime: '2021-08-01', count: 2 },
{ dateTime: '2021-08-02', count: 1 },
{ dateTime: '2021-08-03', count: 2 },
{ dateTime: '2021-08-04', count: 3 }
]
I want to reduce it to something like this:
[
{ month: '2021-07', count: 5 },
{ month: '2021-08', count: 8 }
]
Here's the snippet:
const data = [{
dateTime: '2021-07-30',
count: 4
},
{
dateTime: '2021-07-31',
count: 1
},
{
dateTime: '2021-08-01',
count: 2
},
{
dateTime: '2021-08-02',
count: 1
},
{
dateTime: '2021-08-03',
count: 2
},
{
dateTime: '2021-08-04',
count: 3
}
];
const stackedMonths = data.reduce((acc, curr) => {
return [{
month: curr.dateTime.slice(0, 7),
count: acc + curr.count
}];
}, []);
console.log(stackedMonths);
After trying the code, I'm getting this which doesn't make any sense:
[ { month: '2021-08', count: '[object Object]2' } ]
What am I doing wrong here? Please note that I'm new to reduce and I'm still learning it.
count: acc + curr.count,accis an object. When you concatenate an object with a number, you get a string (unless you have a toValue method on the object that returns a number.) Surely you didn't intend to concatenate an object with a number?[object Object]2. Yes, arrays are objects, but arrays have a different outcome when concatenating in this way