

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of all positives present in an array in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers (positive and negative). Our function should calculate and return the sum of all the positive numbers present in the array.
Example
Following is the code −
const arr = [5, -5, -3, -5, -7, -8, 1, 9]; const sumPositives = (arr = []) => { const isPositive = num => typeof num === 'number' && num > 0; const res = arr.reduce((acc, val) => { if(isPositive(val)){ acc += val; }; return acc; }, 0); return res; }; console.log(sumPositives(arr));
Output
Following is the console output −
15
- Related Questions & Answers
- Given an array of integers return positives, whose equivalent negatives present in it in JavaScript
- Sum of all prime numbers in an array - JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Sum of XOR of sum of all pairs in an array in C++
- Sum all duplicate value in array - JavaScript
- Sum of XOR of all pairs in an array in C++
- Sum of distinct elements of an array in JavaScript
- Sum all duplicate values in array in JavaScript
- Sum all similar elements in one array - JavaScript
- Sum of distinct elements of an array - JavaScript
- Moving all zeroes present in the array to the end in JavaScript
- Sum of all multiples in JavaScript
- Finding sum of a range in an array JavaScript
- Finding desired sum of elements in an array in JavaScript
- Product of all other numbers an array in JavaScript
Advertisements