Returning the value of (count of positive / sum of negatives) for an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 ]
raja
Published on 19-Apr-2021 10:43:44
Advertisements