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



Problem

We are required to write a JavaScript function that takes in a mixed array of number and string representations of integers.

Our function should add up okthe string integers and subtract this from the total of the non-string integers.

Example

Following is the code −

 Live Demo

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

Output

Following is the console output −

10
Updated on: 2021-04-19T08:06:43+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements