Positive, negative and zeroes contribution of an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose we have an array of integers, (positive, negative and zero) like this −

const arr = [23, -1, 0, 11, 18];

We are required to write a JavaScript function that takes in one such array as the first and the only argument. The function should then find the fractional ratio for all three different groups, namely positive, negative and zero.

For example −

For the above array, its length is 5, the output for this array should be −

const output = [.2, .2, .6];

The output array will always contain 3 numbers, representing the fractional ratio of negative, zero and positive integers respectively. One rough way to verify our answer is to add these three values and check if they near 1 or not, if they do, we are very likely to have solved the problem correctly.

Example

The code for this will be −

 Live Demo

const arr = [23, -1, 0, 11, 18];
const findRatio = (arr = []) => {
   const { length } = arr;
   const res = [0, 0, 0];
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      const key = el / Math.abs(el || 1);
      res[key + 1]++;
   };
   return res.map(el => el / length);
};
console.log(findRatio(arr));

Output

And the output in the console will be −

[0.2, 0.2, 0.6]
raja
Published on 22-Feb-2021 09:43:42
Advertisements