Max T
Max T

Reputation: 1455

Return the sum of the array with decimal numbers JavaScript

I have a function that takes the array of score and needs to calculate the average score. This works with regular numbers, but doesn't work when the score number has a decimal. How do I change this function to solve this? We don't want to cut the decimals of course.

const score = [ "3.0", "3.2", "4.4" ]

const result = (survey
        .map( function(i){ // assure the value can be converted into an integer
        return /^\d+$/.test(i) ? parseInt(i) : 0; 
      })
      .reduce( function(a,b){ // sum all resulting numbers
        return (a+b) 
      })/score.length).toFixed(1)

Upvotes: 0

Views: 4569

Answers (2)

Andrei Balmus
Andrei Balmus

Reputation: 1

You could simply use recursion:

function sum(a) {
  return (a.length && parseFloat(a[0]) + sum(a.slice(1))) || 0;
}

sum([ "3.0", "3.2", "4.4" ]).toFixed(1); // 10.6

Upvotes: 0

JasonB
JasonB

Reputation: 6368

I barely changed your code. Adjusted the regex and used parseFloat.

const score = ["3.0", "3.2", "4.4"]

const result = (score
  .map(function(i) { // assure the value can be converted into an integer
    return /^\d+(\.\d+)?$/.test(i) ? parseFloat(i) : 0;
  })
  .reduce(function(a, b) { // sum all resulting numbers
    return (a + b)
  }) /
  score.length).toFixed(1);

console.log(result);

Upvotes: 2

Related Questions