I have an array of objects where I need to find the sum of each array of values. it looks like this
'1664625533491050': [
380.942, 394.71, 387.936, 273.902,
137.58, 133.82, 66.471, 58.616,
45.966, 36.849, 49.002, 32.275,
65.209, 34.679, 60.806, 46.576,
132.89, 62.005, 0.386, 0.09,
0.005, 0.601, 0.004, 0.316,
0.227, 0.185, 0.206, 0.142,
0.1, 0.121, 0.089, 0.016,
0.033, 0.008, 0, 0.002,
0.001
],
'1664625594588444': [
381.931, 394.71, 387.936, 283.902,
146.365, 133.82, 66.471, 58.616,
45.966, 36.849, 49.002, 32.275,
64.953, 34.679, 60.806, 46.576,
132.889, 68.005, 0.386, 0.09,
0.005, 0.601, 0.004, 0.316,
0.227, 0.185, 0.206, 0.142,
0.1, 0.121, 0.089, 0.016,
0.033, 0.008, 0, 0.002,
0.001
]
}
for each object I need to find the sum of each array. I believe that I need to map and reduce each one but I am unsure how to reference each array
function getSum(obj) {
for (const key in obj) {
const firstStep = obj[key];
const secondStep = firstStep.map(x => x/*not sure how to reference*/);
const thirdStep = secondStep.reduce((a, b) => a + b);
obj[key] = thirdStep
return obj
}
How can I reference the array so that I can get the sum of each objects array?
example
'1664625533491050': 2345.789,
'1664625594588444': 1789.587
// those aren't the actual totals just example of what Im looking to get
1664625533491050and1664625594588444- what is it you're trying to do infirstStep.map??? note, map callback gets 3 arguments,(currentElement, currentIndex, wholeArray)- so, perhaps the third argument is what you want? though, looking at it again, it looks like you don't need your themapstep at all, you just need to thereducereturn objinside the for loop that is short circuiting the loop so only one property is processed? Is that the actual issue? There's no need to return the incomingobjsince your code mutates the incoming objreturn objoutside of the loop and it's working fine. thanks!!