JavaScript Array find ()

O método find () do array JavaScript retorna o valor do primeiro elemento do array que satisfaz a função de teste fornecida.

A sintaxe do find()método é:

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

Aqui, arr é um array.

find () Parâmetros

O find()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 find ()

  • Retorna o valor do primeiro elemento da matriz que satisfaz a função fornecida.
  • Retorna indefinido se nenhum dos elementos satisfizer a função.

Exemplo 1: Usando o método find ()

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

Resultado

 8 1

Exemplo 2: find () 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.find(isAdult)); // ( name: 'Alan', age: 20 ) // using arrow function and deconstructing adultMember = team.find((( age )) => age>= 18); console.log(adultMember); // ( name: 'Alan', age: 20 )

Resultado

 (nome: 'Alan', idade: 20) (nome: 'Alan', idade: 20)

Leitura recomendada: JavaScript Array.findIndex ()

Artigos interessantes...