How to return the last element of the array using the for method?

Asked

Viewed 502 times

1

I wanted to know how I got the last element of array using the structure for in the case of decreasing?

This is my code:

const a = n => n % 2 === 0;
function callbackfn (valorInserido, funcao) {
  for (valorInserido.length; i=0; i--) {
    if (funcao(valorInserido[i])) {
      return valorInserido[i];
    }
  }
}
console.log(callbackfn([3,5,2,4],(a)));

In case it was to return the number 4, but returns undefined.

  • This code has syntax errors and does not seem to do what is described in the question. You can clarify?

  • @Maniero it is a code that has the same function as the find however, I want to do a findLast and I’m not getting it. I just want to make it take the last value that returns true. o findtakes the first value that returns true, I want to take the last.

  • You don’t need for uses array[array.length - 1] that will return the last element

  • @Pedropinto he wants conditionally

1 answer

2


The code has several errors.

The variable is not initialized i and has to initialize with the number of elements minus 1, since it starts from scratch. The ending condition of the loop should be as i is greater than or equal to 0. If you ask if it is equal to 0, it will never be, unless the array has no elements, which doesn’t matter. And in fact if it were the same, it would be the ==, the = is attribution.

I improved the style.

const condicao = n => n % 2 === 0;
function PegaUltimoCondicionalmente(valorInserido, funcao) {
  for (var i = valorInserido.length - 1; i >= 0; i--) if (funcao(valorInserido[i])) return valorInserido[i];
}
console.log(PegaUltimoCondicionalmente([3, 5, 2, 4], condicao));

I put in the Github for future reference.

  • Caraca, thank you, <3

  • In this case, it’s not even the last, it’s the last pair. :)

  • A doubt, the code var i = valorInserido.length - 1, this -1 moves it down a position? Or it reverses the array ?

  • he subtracts one, nothing more. Do you know math? do the math.

Browser other questions tagged

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