javascript – Percentage of numbers greater than, equal to, and less than 0 in an array

Question:

I am trying to generate a function that is parameterized and returns an array with results in percentage following an order. The final result must be an array that shows the percentage of values ​​greater than zero, equal to zero, and less than zero.

Example:

masMenos(1,2,0,-1) 

should result in:

0.5, 0.25, 0.25

Where 0.5 is the percentage of numbers greater than 0, 0.25 equal to zero and 0.25 less than zero.

Any suggestion?

 var array=[1,2,0,-1]; function masMenos(array){ var cantidad=1; for(var i =0;i<array.length;i++){ if(array[i]>0){ cantidad=(array[i]*cantidad)/100; }else if(array[i]==0){ cantidad=(array[i]*cantidad)/100; }else { cantidad=(array[i]*cantidad)/100; } }return cantidad; } console.log(masMenos(1,2,0,-1));

Answer:

You can do it in a simple way with the filter() function:

    function masMenos(array){
      may=array.filter(num => num>0);
      igu=array.filter(num => num==0);
      men=array.filter(num => num<0);
      return {
        mayores: may.length/array.length,
        iguales: igu.length/array.length,
        menores: men.length/array.length
      };
    }
    
    console.log(masMenos([1,2,-1,0,1,0,1,0]));

The filter() function filters the values ​​of the array according to a given function (in this case if they are positive, negative or zero).

Although this method is simple and readable, it is not the most optimal, since each time this function is used, the array is traversed once.

A more optimal and recommended option that uses a single loop is the following:

function masMenos(array, res=[0,0,0], n=array.length) {
    for (i in array)
      array[i]>0 ? res[0]++ : array[i]<0 ? res[2]++ : res[1]++
    return res.map(a =>a/n);
  }

  console.log(masMenos([1,2,-1,0,1,0,1,0]));

Of course the most optimal answers lose readability.

I hope the solution has been clearer, greetings.

Scroll to Top