I am trying to generate a function that is parameterized and returns an array with results in percentage following an order. The final result should be an array showing 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));
You can do it simply with the function
filter()
:The function
filter()
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 that function is used, the array is traversed once.
A more optimal and recommended option that uses a single loop is the following:
Of course the most optimal answers lose legibility.
I hope that the solution has been clearer, greetings.
If you want it to show you three results, you need to declare and return an array, not a simple variable. You can do it like this:
The most optimal thing would be to solve it in a single iteration, and it can be using
for
, as they have already answered, orforEach
:dividing the quantity by the whole can be avoided if one does the sum of the parts
1/largo
, because we apply the distributive property (1+2)/2 = (1/2)+(2/2) .Using
reduce()
is almost the same: