- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements