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));
7

Using typeof for Better Type Checking

The above approach using +el has issues with truthy/falsy values. A more reliable method uses typeof to check for numbers:

const arr = [1, 2, 'a', 4, 0, null, undefined, 3.5];
const sumNumbers = (arr = []) => {
    let sum = 0;
    for(let i = 0; i < arr.length; i++){
        if(typeof arr[i] === 'number' && !isNaN(arr[i])){
            sum += arr[i];
        }
    }
    return sum;
}
console.log(sumNumbers(arr));
10.5

Using Array Methods

A more functional approach using filter() and reduce():

const arr = [1, 2, 'hello', 4, true, 3.14, null];
const sumNumbers = (arr) => {
    return arr
        .filter(item => typeof item === 'number' && !isNaN(item))
        .reduce((sum, num) => sum + num, 0);
}
console.log(sumNumbers(arr));
10.14

Comparison

Method Handles 0? Handles NaN? Readability
Using +el No - skips 0 No Less clear
Using typeof Yes Yes Clear
Array methods Yes Yes Most readable

Conclusion

Use typeof item === 'number' && !isNaN(item) for reliable number checking. The array methods approach provides the cleanest, most functional solution.

Updated on: 2026-03-15T23:19:00+05:30

436 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements