Return only the positive values of an array

Asked

Viewed 333 times

1

Ask me to do a function, which takes a parameter (array) and return positive balances (profitably) of that month, using for and probably a if.

Example:

saldosDeMesesComLucro([100, 20, 0, -10, 10]); 

Exit

// deve retornar [100, 20, 10].

I tried to:

function saldoDeMesesComLucro(saldos){
  for(var i = 0; i < saldos.length; i++){
    if(saldos[i] > 0){
     return saldos;
    }
  }
}

But it’s not the right logic?

3 answers

2

you get the same result using the filter, thus:

let saldoPositivo = [100, 20, 0, -10, 10].filter(saldo=> saldo>0)

console.log(saldoPositivo)

1


In your code, when finding a positive balance the function is stopped and the entire array is returned, without any change.

In the following code, positive values are inserted into a new array, and after going through all values of the original array, the new array is returned.

function saldoDeMesesComLucro(saldos){
  saldosPositivos = [];

  for(var i = 0; i < saldos.length; i++){
    if(saldos[i] > 0){
     saldosPositivos.push( saldos[i] );
    }
  }

  return saldosPositivos;
}
  • You can also use the map to return a new array the way you want const valoresPositivos = saldos.map(item => item > 0)

  • Yes, but I found this way simpler for those who apparently don’t have much experience.

0

But it’s not the right logic?

Not its logic is wrong because at the moment it finds the balance of a certain position the code will return everything again and must save the value of the search in some variable to then return only the values that were satisfied in the comparison.

How the code should be, example:

const saldos = [100,-1,-2,-9,50,10,-8];

function retornarSaldosPositivos(saldos) {
  let sp = [];
  for(let i = 0; i < saldos.length; i++){
    if (saldos[i] > 0) {
      sp.push(saldos[i]);
    }
  }
  return sp;
}

console.log(retornarSaldosPositivos(saldos));

Or in a simplified way with a filter:

const saldos = [100,-1,-2,-9,50,10,-8];

const saldosPositivos = saldos.filter(function(s){
  return s > 0;
}, saldos);

console.log(saldosPositivos);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.