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 −

 Live Demo

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 ]
Updated on: 2021-04-19T10:54:17+05:30

546 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements