JavaScript Array.find() Method
Shubham Vora
Jan 30, 2023
-
Syntax of JavaScript
array.find()
Method -
Example Codes: Use
array.find()
to Get a Single Element From the Given Array -
Example Codes: Use
array.find()
to Find the First Word That Matches the Condition From an Array
In JavaScript, the array.find()
method is used to find the first element from the index position that matches the various condition provided in the callback function()
.
Syntax of JavaScript array.find()
Method
refarray.find(function(currentValue));
refarray.find(function(currentValue, index, arr));
Parameters
callback function() |
To check first the element that matches the condition in the given array. |
currentValue |
The element’s current value is required to test the condition of callback function() . |
index |
The element’s index is optional and can be used depending on the mentioned condition. |
arr |
The element’s array is optional and can be added to check the condition for each element. |
Return
This method returns an element from the given array that fulfills the condition mentioned in the callback function()
.
Example Codes: Use array.find()
to Get a Single Element From the Given Array
let num = [1, 7, 4, 12, 8];
function ismult(thr){
return thr % 3 == 0;
}
let thrMult = num.find(ismult);
console.log(thrMult);
Output:
12
We used the array.find()
method to find a multiple of 3 and return it.
Example Codes: Use array.find()
to Find the First Word That Matches the Condition From an Array
const bio = ["javascript", "java", "web"];
const findWord = bio.find(word);
function word(value, index, arr) {
return bio.includes("java");
}
console.log(findWord);
Output:
javascript
We have created an array of different words. We pass the currentValue
, index
, and arr
as the parameters in the array.find()
function to find the first word from the index position of an array.
Author: Shubham Vora