Array JavaScript findIndex ()

O método findIndex () do array JavaScript retorna o índice do primeiro elemento do array que satisfaz a função de teste fornecida ou então retorna -1.

A sintaxe do findIndex()método é:

 arr.findIndex(callback(element, index, arr),thisArg)

Aqui, arr é um array.

Parâmetros findIndex ()

O findIndex()método inclui:

  • callback - Função a ser executada em cada elemento da matriz. Inclui:
    • element - o elemento atual da matriz.
  • thisArg (opcional) - Objeto a ser usado como thisretorno de chamada interno.

Valor de retorno de findIndex ()

  • Retorna o índice do primeiro elemento da matriz que satisfaz a função fornecida.
  • Retorna -1 se nenhum dos elementos satisfizer a função.

Exemplo 1: Usando o método findIndex ()

 function isEven(element) ( return element % 2 == 0; ) let randomArray = (1, 45, 8, 98, 7); firstEven = randomArray.findIndex(isEven); console.log(firstEven); // 2 // using arrow operator firstOdd = randomArray.findIndex((element) => element % 2 == 1); console.log(firstOdd); // 0

Resultado

 2 0

Exemplo 2: findIndex () com elementos Object

 const team = ( ( name: "Bill", age: 10 ), ( name: "Linus", age: 15 ), ( name: "Alan", age: 20 ), ( name: "Steve", age: 34 ), ); function isAdult(member) ( return member.age>= 18; ) console.log(team.findIndex(isAdult)); // 2 // using arrow function and deconstructing adultMember = team.findIndex((( age )) => age>= 18); console.log(adultMember); // 2 // returns -1 if none satisfy the function infantMember = team.findIndex((( age )) => age <= 1); console.log(infantMember); // -1

Resultado

 2 2 -1

Leitura recomendada: JavaScript Array find ()

Artigos interessantes...