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 −

 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: 19-Apr-2021

434 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements