JavaScript array find() function is “used to get a value of the first element in the array that satisfies the provided test function”.
Syntax
array.find(function(element, index, array),thisValue)
Parameters
- element: This is the current item being processed by the function.
- index: This is the index of the current element processed by the function.
- array: This is the array on which the array.filter() function was called.
- thisValue: It tells the function to use the array value when executing an argument function.
Example 1: Using the find() method
var data = [20, 18, 15, 10, 9];
var found = data.find(function(element) {
return element < 12;
});
console.log(found);
So, we have written one condition. If any array item satisfies this condition, it will return the value of that element, and the further checking of elements inside an array will be stopped.
Here, both the values 10 and 9 are less than 12, but still, we got the 10 because the 10 value of an item is first inside an array.
So only 10 will return and not 9. If the satisfying condition element is found inside an array, it will immediately return, and no further checking is required.
10
Example 2: Passing an arrow function to the find() function
const data = [20, 18, 15, 10, 9];
let found = data.find(element => element < 12);
console.log(found);
The answer will be the same as the previous one, but it is a much lighter syntax.
Now, let us take a scenario where undefined is found.
const data = [20, 18, 15, 10, 9];
let found = data.find(element => element < 9);
console.log(found);
In the above example, the output will be undefined if all elements exceed 9.
Example 3: Apply a find() function to the array of objects in JavaScript
const fruits = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const getFruit = fruits.find(fruit => fruit.name === 'apples');
console.log(getFruit);
Only one object will be returned if the condition is met successfully.
{ name: 'apples', quantity: 2 }
So, whenever we have a scenario where we need to get a value of the first element in an array that satisfies the provided testing function, we can use Array.find() method in JavaScript.
Example 4: Using the index parameter
Here’s how you can use the index parameter:
const student = [
{ name: "krunal", rollno: 21},
{ name: "ankit", rollno: 19},
{ name: "rushabh", rollno: 18}
];
const result = student.find((tree, i) => {
if (tree.rollno > 10 && i !== 0) return true;
});
console.log(result)
Output
{ name: 'ankit', rollno: 19 }
That’s it.
it`s a great tutorial thanks