3
\$\begingroup\$

I wrote a function that checks what's the ratio of the number of positive, negative and null values inside an array in relation to its length. The code I wrote is the following:

function plusMinus(arr) {

    /**first I declare 3 variables to store the positive, negative and null elements inside them*/

    let numPositive = [];
    let numNegative = [];
    let numZero = [];

    /**then I write a loop that will check whether 
    the elements of the input array are positive, negative or null,
    e.g. if the element[i] is positive, then the array 
    numPositive pushes the positive element[i] inside it, 
    and so on for the rest of the numbers and arrays*/

    for (let i=0; i<arr.length;i++){
        if (arr[i]>0){
            numPositive.push(arr[i]>0);
        }else if (arr[i]<0){
            numNegative.push(arr[i]<0);
        }else{
            numZero.push(arr[i]==0)
        }
    }

    /**finally, the ratios are given as a result of 
    the length of the pushed arrays and the length of the original array*/

    console.log(numPositive.length/arr.length);
    console.log(numNegative.length/arr.length);
    console.log(numZero.length/arr.length);
}

I'd like receive some feedback on why my code's logic doesn't work.

\$\endgroup\$
  • \$\begingroup\$ You could just count the elements in each class and use the count instead of saving three sub arrays and get their lengths \$\endgroup\$ – mdexp Jan 20 at 0:52
  • \$\begingroup\$ Can you explain little bit more here along with few sample inputs and outputs. Also, does the array made entirely of numbers only? You mentioned positive, negative and null values but in the loop, you are checking only for positive and negative values. Everything else will go in the third loop (null, 0). There might be the issue. \$\endgroup\$ – Sunil Chaudhary Jan 20 at 1:31

Browse other questions tagged or ask your own question.