
- 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
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 Articles
- 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 all duplicate value in array - JavaScript
- Sum all duplicate values in array in 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++
- How to store all dates in an array present in between given two dates in JavaScript?
- Sum all similar elements in one array - JavaScript
- Sum of XOR of all pairs in an array in C++
- Sum of distinct elements of an array in JavaScript
- Moving all zeroes present in the array to the end 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
- Finding all possible subsets of an array in JavaScript

Advertisements