I have the following code on my React app:
var numberOfAnswers = 0
var sumOfAnswers = 0
respostas.forEach(function (element,index) {
console.log(index+"-"+element["responses"])
numberOfAnswers += element["responses"]
sumOfAnswers += (index*element["responses"])
})
it works perfectly, but I want to use something like that:
const arrSum = respostas => respostas.reduce((a,b) => a + b, 0)
Is it possible to do that using reduce() and if it is possible, how can I do that?
sure, it is possible
const [numberOfAnswers, sumOfAnswers] = respostas.reduce((res, element, index) =>
[
res[0] + element.responses,
res[1] + index * element.responses
] , [0, 0])
With reduce, you can instantiate your variables by having them as a default object (see 2nd argument), then populate that object as you iterate over the array. The first argument of reduce accepts a callback function, in which that function accepts 3 arguments, the total object, current item being iterated over and its index. On each iteration, you populate that object and return it so the next iteration has access to the updated data.
Try something like this:
let data = repostas.reduce((object, current, index) => {
object.numberOfAnswers += current["responses"]
object.sumOfAnswers += (index * current["responses"])
return object
}, { numberOfAnswers: 0, sumOfAnswers: 0})
Then you can just access your points via the data object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With