
- 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
Returning the value of (count of positive / sum of negatives) for an array in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers (positives and negatives) and our function should return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.
Example
Following is the code −
const arr = [1, 2, 1, -2, -4, 2, -6, 2, -4, 9]; const posNeg = (arr = []) => { const creds = arr.reduce((acc, val) => { let [count, sum] = acc; if(val > 0){ count++; }else if(val < 0){ sum += val; }; return [count, sum]; }, [0, 0]); return creds; }; console.log(posNeg(arr));
Output
[ 6, -16 ]
- Related Articles
- Count groups of negatives numbers in JavaScript
- Returning the highest value from an array in JavaScript
- Sum array of rational numbers and returning the result in simplest form in JavaScript
- Given an array of integers return positives, whose equivalent negatives present in it in JavaScript
- Removing Negatives from Array in JavaScript
- Reverse index value sum of array in JavaScript
- Accessing and returning nested array value - JavaScript?
- Returning reverse array of integers using JavaScript
- Returning the value of nth power of iota(i) using JavaScript
- JavaScript Algorithm - Removing Negatives from the Array
- Positive, negative and zeroes contribution of an array in JavaScript
- Sum of distinct elements of an array in JavaScript
- Find Count of Positive, Negative and Zero Elements in an Array in Java
- Sum of distinct elements of an array - JavaScript
- Count the number of data types in an array - JavaScript

Advertisements