![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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 ]
Advertisements