Go through an array and sum only numbers JavaScript


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

Updated on: 21-Nov-2020

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements