
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 −
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
- Related Articles
- Distance between 2 duplicate numbers in an array JavaScript
- Picking all the numbers present in a string in JavaScript
- Validating a string with numbers present in it in JavaScript
- Maximum consecutive numbers present in an array in C++
- Product of numbers present in a nested array in JavaScript
- Absolute Difference between the Product of Non-Prime numbers and Prime numbers of an Array?
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Summing numbers present in a string separated by spaces using JavaScript
- Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
- Summing array of string numbers using JavaScript
- Non-composite numbers sum in an array in JavaScript
- Difference between composite numbers and prime numbers.
- Sum of all prime numbers in an array - JavaScript
- Product of all other numbers an array in JavaScript
- Repeating only even numbers inside an array in JavaScript

Advertisements