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 −
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