3

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?

2 Answers 2

1

sure, it is possible

const [numberOfAnswers, sumOfAnswers] = respostas.reduce((res, element, index) => 
  [
    res[0] + element.responses, 
    res[1] + index * element.responses
  ] , [0, 0])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.