- 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
Go through an array and sum only numbers JavaScript
We are required to write a JavaScript function that takes in an array. The array might contain any type of value, Number literals, string literals, objects, undefined.
Our function should pick all the Number type values and return their sum
Example
const arr = [1, 2, 'a', 4]; const countNumbers = (arr = []) => { let sum = 0; for(let i = 0; i < arr.length; i++){ const el = arr[i]; if(+el){ sum += +el; }; }; return sum; } console.log(countNumbers(arr));
Output
And the output in the console will be −
7
Advertisements