2

I'm trying to reduce an array of numbers into the sum of all the numbers combined. At the moment I'm using Array.reduce to try and achieve this, but what I'm finding is that this function only stacks the array's values to create one massive number rather than summing them all together.

// Function used to get the sum of all numbers in array

function getSum(total, num){
    return total + num; 

// Reduce Var 

var easternSum = scoreEastern.reduce(getSum);

// Dynamic array based on user input

var scoreEastern = dataSet
                    .filter(scoreEastern => scoreEastern.Course === 'eastern')
                    .map(({Score}) => Score);

// Empty array that scoreEastern var is assigned to

var dataSet = [];

Because my array is dynamic, it's based on what the user inputs into a form, there's no set array. But let's say the array is:

var scoreEastern = [10, 20, 30]

The reduce var easternSum will result in the number 102,030. What I want is 60.

jamierossiter
  • 47
  • 1
  • 1
  • 6

1 Answers1

0

I think maybe scoreEastern doesn't have the data that you expect all the time? You mentioned that it is dynamic. This snippet appears to work for the use case you posted in your question.

const scoreEastern = [10, 20, 30];

console.log(scoreEastern.reduce((prev, curr) => prev + curr));
Daniel Cottone
  • 4,257
  • 24
  • 39