find method
The find
method helps to find the
first element in an array according to the
callback
passed in the parameter. If there is no
element, then undefined
is returned.
Syntax
array.find(function);
Example
Let's find the array element that matches the conditions specified in a function:
let arr = [1, 2, 3, 4];
let res = arr.find(function(currentValue) {
return currentValue > 0;
});
console.log(res);
The code execution result:
1
Example
Let's find an array element
whose length is 2
:
let arr = ['abc', 'defg', 'kl', 'mn'];
let res = arr.find(function(elem) {
return elem.length == 2;
});
console.log(res);
As a result of executing the code, we will see that the method found the first element that matches the conditions of the function:
'kl'
See also
-
the
findIndex
method
that searches for the index of an element in an array -
the
findLast
method
that searches for an element from the end of an array -
the
findLastIndex
method
that searches for the index of an element from the end of an array