
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Count Positive and Sum 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 ]
Advertisements