JavaScript's find() method
Details, examples, practice
When you need to find the first value in an array that satisfies a certain condition, the best choice is the find() method.
It returns the first element that satisfies your defined callback function. If nothing matches, it returns undefined.
array.find(function(element, index, array) { // returns true/false });
Parameters
const users = [ { id: 1, name: 'Anna' }, { id: 2, name: 'David' }, { id: 3, name: 'Levon' } ]; const foundUser = users.find(user => user.id === 2); console.log(foundUser); // { id: 2, name: 'David' }
Returns the first user whose id is equal to 2.
Example
const result = users.find(user => user.id === 5); console.log(result); // undefined
const even = [1, 2, 3, 4, 5].find(n => n % 2 === 0); // 2 const evenList = [1, 2, 3, 4, 5].filter(n => n % 2 === 0); // [2, 4]
When we call:
[1, 2, 3].find(fn);
This is the same as:
Array.prototype.find.call([1, 2, 3], fn);
function myFind(array, callback) { for (let i = 0; i < array.length; i++) { if (callback(array[i], i, array)) { return array[i]; } } return undefined; }
Usage example:
const items = [10, 20, 30, 40]; const found = myFind(items, function(item) { return item > 25; }); console.log(found); // 30
Array.prototype.myFind = function(callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { return this[i]; } } return undefined; };
We use it like this:
const numbers = [5, 10, 15, 20]; const found = numbers.myFind(n => n > 10); console.log(found); // 15