Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
How to loop through array with FindIndex from its end?

I need to get errorIdx = 3, but I get 0. How can I loop through array from its end?

  const scrollPosition = 5007
  const errorsHeight = [947, 2498, 3495, 4805, 5755]

  errorIdx = errorsHeight.findIndex((itemHeight: number) => itemHeight < scrollPosition)
  console.log(errorIdx) // 0
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

An alternative implementation of findLastIndex where the callback function is aware of a thisArg context/target and also will be invoked with its three parameters which are [element, index, array]; thus following the standard of findIndex ...

function findLastIndex(arr, test, target) {
  if (!arr && ((arr ?? true) === true)) {
    throw new TypeError('findLastIndex called on null or undefined');
  };
  if (typeof test !== 'function') {
    throw new TypeError(`${ test } is not a function`);
  };
  if (!Array.isArray(arr)) {
    arr = Array.from(arr);
  }
  target = target ?? null;

  let isContinue = true;
  let idx = arr.length;

  // assures -1 as return value for nothing found.
  while ((idx >= 0) && isContinue) {

    // be aware of sparse array slots ... and ...
    // be a guard for the negative index default.
    if (arr.hasOwnProperty(--idx)) {

      isContinue = !test.call(target, arr[idx], idx, arr);
    }
  }
  return idx;
}

const errorsHeight = [947, 2498, 3495, 4805, 5755];
const scrollPosition = 5007;

console.log(
  findLastIndex(errorsHeight, (height/*, idx, arr*/) =>
    height < scrollPosition
  )
);
console.log(
  findLastIndex(errorsHeight, height => height < 5)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

Resorting the array or reversing it adds an extra O(n) to your solution.

The simple approach is to just make a helper function that finds the index starting from the end of the array:

function findLastIndex(arr, comparator){
    for(let i = arr.length - 1; i > 0; i--){
        const valid = comparator(arr[i], i);
        if(valid){
            return i;
        }
    }

    return -1;
}


console.log(findLastIndex(errorsHeight, (itemHeight: number) => itemHeight < scrollPosition))
about 4 years ago · Juan Pablo Isaza Relatório

0

Better do with a simple for, like this:

const scrollPosition = 5007;
const errorsHeight = [947, 2498, 3495, 4805, 5755];
let errorIdx = -1;

for (let i = 0; i < errorsHeight.length; i++)
    if((errorIdx === -1 && errorsHeight[i] < scrollPosition) || (errorIdx >= 0 && errorsHeight[i] < scrollPosition && errorsHeight[i] > errorsHeight[errorIdx]))
        errorIdx = i;

console.log(errorIdx) //3
;D

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda