javascript – Check the amount of negative elements in a JS array

Question:

I'm starting to study Javascript and I come across a question where I need to identify negative elements in an array and return the amount of these numbers. Remembering that there can be empty, mixed(+ and -), negative and positive arrays.

I tried to do it with this one, but it's not working:

   function quantidadeDeMesesComPerda(umPeriodo){
  let quantidade =0;
  let somaDeElementosNeg = 0;
  let somaDeElementosPosit=0;
  let elementos =0;
  for(var i = 0; i < umPeriodo.length; i++){  
    elementos = umPeriodo[i];
    somaDeElementosNeg+=i;
    somaDeElementosPosit-=i;
        if(elementos < 0){
          quantidade = somaDeElementosNeg;
            return quantidade.length;
      } else if(elementos >0){
        quantidade = somaDeElementosPosit;
            return quantidade.length - somaDeElementosNeg.length;;
      } else {
        return 0;
      }   
  } 
}

Answer:

What you need is:

function quantidadeDeMesesComPerda(umPeriodo) {
  return umPeriodo.filter(nr => nr < 0).length;
}

const test = quantidadeDeMesesComPerda([10, -10, 2, 100]);
console.log(test);

That is, with the .filter you go through the array and exclude all positive numbers or zero. At the end, returning .length you will know how many undeleted were left.

The code you have had several problems… for example:

  • somaDeElementosNeg += i;

    here you are adding in each count of i which doesn't make sense because aPeriod[i] can be positive or negative

  • return quantidade.length;

    a number does not have .length , what you want is the "quantity" itself without .length
    another problem is the return it will cancel the "for loop" and give you an answer before analyzing all the elements…

If you want to do it with a for , using an incremental variable you can do it like this:

function quantidadeDeMesesComPerda(umPeriodo) {
  let perdas = 0;
  for (let i = 0, l = umPeriodo.length; i < l; i++) {
    if (umPeriodo[i] < 0) perdas++;
  }
  return perdas;
}

const test = quantidadeDeMesesComPerda([10, -10, 2, 100]);
console.log(test);
Scroll to Top