JavaScript ArrayFind
The find()
method returns the value of the first array element that satisfies the provided test function.
Syntax
arr.find(callback(element, index, arr),thisArg)
arr
– An array.
Parameters
callback
– A callback function to test each element of the array.element
– The current element of the array.index
– Optional. The index of the current element within the array.arr
– Optional. A reference to the original array.thisArg
– Optional. A parameter that will be used as this within the callback function.
Returns
Returns the value of the first element in the array that satisfies the given function. Returns undefined
if none of the elements satisfy the function.
find in javascript
Using find() method
const names = [ "Adam", "Benny", "Zen", "Joey" ]; const output = names.find(name => name.startsWith("B")); console.log(output)
Output
Benny
find() with Object elements
const names = [ { name : "Adam", grade : 8.5 }, { name : "Benny", grade : 7.5 }, { name : "Zen", grade : 9.5 }, { name : "Joey", grade : 6.5 } ]; const output = names.find(({ grade }) => grade > 8.5); console.log(output)
Output
{ name: 'Zen', grade: 9.5 }
Note:The
find()
method does not modify the original array.
const students = [ { name : "Adam", age : 18 }, { name : "Benny", age : 17 }, { name : "Zen", grade : 19 }, { name : "Joey", grade : 21 } ]; function isAdult({ age }) { return age >= 18; } const output = students.find(isAdult); console.log(output)
Output
{ name: 'Adam', age: 18 }
Browser Support
find()
is an ES6 feature. It is supported in all modern browsers.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Yes | Yes | Yes | Yes | Yes |