Whenever I'd like to use reduce inside a map function I get the error 'reduce is not a function'.
I've got an array where I'm mapping through 2 keys. Date and Amount. Below is the array with objects.
const dividendArrayFiltered = [
{
"date": "2021-11-09",
"amount": 0.5
},
{
"date": "2021-11-08",
"amount": 0.5
},
{
"date": "2021-11-08",
"amount": 0.5
},
{
"date": "2021-11-11",
"amount": 1
},
{
"date": "2021-11-11",
"amount": 1
}
]
Within this map I'd like to reduce the values with the same date.
This is the code that is giving the error. Not quite sure why the reduce function is not working. Hope you could help me out. Thanks!
const summedDividend = dividendArrayFiltered.map(({ date, amount }) => {
const grouped = date.reduce(
(a, d, i) => a.set(d, (a.get(d) ?? 0) + amount[i]),
new Map()
);
return {
date: [...grouped.keys()],
amount: [...grouped.values()],
};
});
Your own solution isn't working because inside the map-function you have only access on the current item, not the array, but the reduce-function can only be used on arrays.
Alternative Solution:
You can create an empty array, where you push only these items from your origin array, which haven't the same date like one of the items in your new array.
let uniqueArray = []
// iterate through all array elements
dividendArrayFiltered.forEach((item) => {
// check if an element with the current item date exists in your new uniqueArray and which position index it has
const itemPos = uniqueArray.findIndex(uniqueItem => uniqueItem.date == item.date)
// if the index is negative, it's not included in the array, so you push your item to the new array
if(itemPos < 0) {
uniqueArray.push(item)
}
// if it's included, you take the old amount and add your new value
else {
uniqueArray[itemPos].amount = uniqueArray[itemPos].amount + item.amount;
}
});
console.log(uniqueArray);
In uniqueArray are now only unique date items.
You can reduce the original array directly and also utilize findIndex():
const dividendArrayFiltered = [
{ date: '2021-11-09', amount: 0.5 },
{ date: '2021-11-08', amount: 0.5 },
{ date: '2021-11-08', amount: 0.5 },
{ date: '2021-11-11', amount: 1 },
{ date: '2021-11-11', amount: 1 }
]
const grouped = dividendArrayFiltered.reduce((a, c) => {
const dateIndex = a.findIndex(o => o.date === c.date)
if (dateIndex !== -1) a[dateIndex].amount += c.amount
else a.push({ date: c.date, amount: c.amount })
return a
}, [])
console.log(grouped)
.as-console-wrapper { min-height: 100% }