简体   繁体   中英

Compute sum of numerical values of an array in JavaScript

I have the following array:

myArray = [32.4, "bla", 1.44, 0.5, 65.8, "abc"];

To compute the sum of an array containing only digits is pretty straight-forward, but how can it be done if there are also non-numerical values which must be ignored?

Use .reduce and check if the element is number using isNaN()

If you want to add strings which represents a number then you can use:

 var myArray = [32.4, "bla", 1.44, 0.5, 65.8, "abc"]; var sum = myArray.reduce((acc, el) => acc + (!isNaN(el) ? +el : 0)); console.log(sum); 

If you want to ignore string which represents a number "1" then use typeof

 var myArray = [32.4, "bla", 1.44, 0.5, 65.8, "abc"]; var sum = myArray.reduce((acc, el) => acc + (typeof el === "number" ? el : 0)); console.log(sum); 

Parse everything as numbers and check for NaN

var sum = 0
myArray.forEach(el => {
   if(!Number.isNaN(parseFloat(el))) sum += parseFloat(el)
})

This solution also works for array with strings representing numbers like ["4.5", "5", "a", 10] (will give 19.5) If you don't want this behaviour, you'd better check with type of:

var sum = 0
myArray.forEach(el => sum += (typeof el == "number" ? el : 0))

You could use the reduce() function combined with .isNaN() to check if you have a Number.

 var myArray = [32.4, "bla", 1.44, 0.5, 65.8, "abc"]; var res = myArray.reduce(function(acc, curr){ return acc + (isNaN(curr) ? 0 : curr); }); console.log(res); 

You can use array.prototype.filter and array.prototype.reduce :

 var myArray = [32.4, "bla", 1.44, 0.5, 65.8, "abc"]; var sum = myArray.filter(n => !isNaN(n)).reduce((m, n) => m + n); console.log(sum); 

Use reduce and isNaN

var arr = [32.4, "bla", 1.44, 0.5, 65.8, "abc"];
var output = arr.reduce( ( a, c ) => a + ( isNaN( c ) ? 0 : c ), 0 );

Demo

 var arr = [32.4, "bla", 1.44, 0.5, 65.8, "abc"]; var output = arr.reduce( ( a, c ) => a + ( isNaN( c ) ? 0 : c ), 0 ); console.log( output.toFixed(2) ); 

Explanation

  • Use reduce to initialize an accumulator a to 0 .
  • Use isNaN to check if c (array item for current iteration) Is-Not-A-Number (if not add 0 to a )
var numbers = myArray.map(value => {
    value = parseFloat(value);
    return (isNaN(value))? 0: value;
});

Then calculate the sum of numbers

I would even combine two of the answers above and use the common Map Reduce strategy:

var numbers = myArray.map((value) => {
    value = parseFloat(value);
    if(isNaN(value)) value = 0;
}).reduce(function(acc, curr){
  return acc + (isNaN(curr) ? 0 : curr);
});

Of course you could press everything in Map or the reduce function, but as I was taught the Map function prepares the values in a proper form and afterwards the reduces function's goal is only to combine all the available values to a single one using a given function / strategy.

(I'm sorry if there's a syntax error, I'm only coding in Swift atm.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM