Go through an array and sum only numbers JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array. The array might contain any type of value, Number literals, string literals, objects, undefined.

Our function should pick all the Number type values and return their sum

Example

const arr = [1, 2, 'a', 4];
const countNumbers = (arr = []) => {
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      const el = arr[i]; if(+el){
         sum += +el;
      };
   };
   return sum;
}
console.log(countNumbers(arr));

Output

And the output in the console will be −

7
raja
Published on 21-Nov-2020 06:04:46
Advertisements