Help on 2 Arrays questions

Asked

Viewed 1,875 times

0

It has this function to find out how many months a person’s balance was positive:

function quantidadeDeMesesComLucro(umPeriodo){

let quantidade = 0;

for(let mes = 0; mes < umPeriodo.length; mes++){
    if(umPeriodo[mes] > 0)
        quantidade += 1;
}

return quantidade;
}

Now I needed to write a code (in the same structure as this above) to know how many months of a period there was loss (when the balance is less than zero).

Then that would be the first question, to write the function quantity.

To second question would that be:

Knowing the balance of the months with profit

Complete the function saldoDeMesesComLucro. Again it has a structure similar to the previous problems, but not so fast! This function needs to return an array.

balances [100, 20, 10]

Somebody please help me

1 answer

0


Thiago,

In the first problem, it is quite simple, as the function must have the same structure as the function quantidadeDeMesesComLucro, just create the function quantidadeDeMesesComPerda, but with the comparison of inverted values.

In the quantityDesesComLucro function, the value comparison uses the largest >:

if(umPeriodo[mes] > 0)

This condition in the function quantidadeDeMesesComPerda shall have the opposite comparison, using the <, then the function will be as follows:

const meses = [100, 20, 0, -10, 10];

function quantidadeDeMesesComPerda(umPeriodo){
  let quantidade = 0;

  for(let mes = 0; mes < umPeriodo.length; mes++){
    if(umPeriodo[mes] < 0)
      quantidade += 1;
  }

  return quantidade;
}

console.log(quantidadeDeMesesComPerda(meses));


Now by changing the function quantidadeDeMesesComLucro to return an array, we can easily change the variable that is a counter in the function (quantidade) and use an array instead of an array, with quantidade += 1;, we will use the push method of the array:

function quantidadeDeMesesComLucro(umPeriodo){
  let periodos = [];

  for(let mes = 0; mes < umPeriodo.length; mes++){
    if(umPeriodo[mes] > 0)
      periodos.push(umPeriodo[mes]);
  }

  return periodos;
}

const meses = [100, 20, 0, -10, 10];

console.log(quantidadeDeMesesComLucro(meses));

See that I initialized the array with an empty value [], this is important, otherwise an exception will be generated when trying to use the push method.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

  • Ah got it! In the case the reasoning of the function quantityDeMesesComPerda is to return a number, that’s why the counter is used. And in the reasoning of the second function, I’m returning a value within the array right, so the push method. That would be about it?

  • Yeah, that’s right, that’s right.

Browser other questions tagged

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