The find()
method returns the first element by the provided testing function.
arr.find(callback(element[, index[, array]])[, thisArg])
Parameter | Optional | Meaning |
---|---|---|
callback | Not | Function to execute on each array element. It takes 3 arguments: element - current array element index - Optional, the index of the current element. array - Optional, the whole array. |
thisArg | Optional | Object to use as this inside callback. |
const languages = [/*from w ww . j av a 2s. c om*/ {name: 'HTML', line: 2}, {name: 'CSS', line: 0}, {name: 'Javascript', line: 5} ]; function isCSS(fruit) { return fruit.name === 'CSS'; } console.log(languages.find(isCSS)); //using arrow function const result = languages.find( ({ name }) => name === 'CSS' ); console.log(result)
Find a prime number or return undefined if there is no prime number:
function isPrime(element, index, array) { let start = 2;// www . j a va 2 s . c om while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found console.log([4, 5, 8, 12].find(isPrime)); // 5
find()
visits the nonexistent and deleted elements
const array = [0,1,,,,5,6];/*from ww w. j av a2 s.c om*/ array.find(function(value, index) { console.log('Visited index ', index, ' with value ', value); }); array.find(function(value, index) { if (index === 0) { delete array[5]; } // Element 5 is visited even though deleted console.log('Visited index ', index, ' with value ', value); });
More example
const people = [{/*from ww w . j av a 2s. c om*/ name: "CSS", age: 27 }, { name: "HTML", age: 29 } ]; console.log(people.find((element, index, array) => element.age < 28)); console.log(people.findIndex((element, index, array) => element.age < 28));
find()
and findIndex()
will continue searching once a match has been found.
const evens = [2, 4, 6];/*w w w . ja v a 2 s. co m*/ // Last element of array will never be inspected after match is found evens.find((element, index, array) => { console.log(element); console.log(index); console.log(array); return element === 4; });