- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Repeating only even numbers inside an array in JavaScript
- Sum of all prime numbers in an array - JavaScript
- Non-composite numbers sum in an array in JavaScript
- Squared and square rooted sum of numbers of an array in JavaScript
- Looping through an array in Javascript
- Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
- Converting array of Numbers to cumulative sum array in JavaScript
- Sorting only a part of an array JavaScript
- Difference between numbers and string numbers present in an array in JavaScript
- Recursively loop through an array and return number of items with JavaScript?
- Write a number array and using for loop add only even numbers in javascript?
- Loop through array and edit string JavaScript
- Difference between sum and product of an array in JavaScript
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Taking the absolute sum of Array of Numbers in JavaScript

Advertisements