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

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 19-Apr-2021 08:05:51
Advertisements