Difference between numbers and string numbers present in an array in JavaScript

In JavaScript, arrays can contain both numbers and string representations of numbers. This article demonstrates how to differentiate between these types and perform different operations based on their type.

Problem

We need to create a JavaScript function that takes a mixed array of numbers and string representations of integers. The function should add up all numeric values and subtract the sum of string numeric values from this total.

Approach

We'll use typeof to identify data types and the unary plus operator (+) to convert strings to numbers while checking if they're valid numeric strings.

Example

Here's how to implement the solution:

const arr = [5, 2, '4', '7', '4', 2, 7, 9];

const integerDifference = (arr = []) => {
    let res = 0;
    for(let i = 0; i < arr.length; i++){
        const el = arr[i];
        if(typeof el === 'number'){
            res += el;
        }else if(typeof el === 'string' && +el){
            res -= (+el);
        }
    }
    return res;
};

console.log(integerDifference(arr));
10

How It Works

The function processes each array element:

  • If the element is a number type, it's added to the result
  • If the element is a string and converts to a truthy number, it's subtracted from the result
  • The unary plus (+el) converts the string to a number for the calculation

Step-by-Step Calculation

const arr = [5, 2, '4', '7', '4', 2, 7, 9];

console.log("Numbers found:", arr.filter(el => typeof el === 'number'));
console.log("String numbers found:", arr.filter(el => typeof el === 'string'));

// Sum of numbers: 5 + 2 + 2 + 7 + 9 = 25
// Sum of string numbers: 4 + 7 + 4 = 15
// Result: 25 - 15 = 10
Numbers found: [ 5, 2, 2, 7, 9 ]
String numbers found: [ '4', '7', '4' ]

Alternative Using reduce()

A more functional approach using the reduce() method:

const arr = [5, 2, '4', '7', '4', 2, 7, 9];

const integerDifferenceReduce = (arr = []) => {
    return arr.reduce((acc, el) => {
        if(typeof el === 'number'){
            return acc + el;
        }else if(typeof el === 'string' && +el){
            return acc - (+el);
        }
        return acc;
    }, 0);
};

console.log(integerDifferenceReduce(arr));
10

Conclusion

This approach effectively differentiates between numbers and string representations in arrays using typeof checks. The unary plus operator provides a clean way to convert and validate numeric strings for mathematical operations.

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

421 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements