JS: Array.prototype.find
New in JS2015.
arrayX.find(f)
-
- Return the first element of array arrayX where the function f returns
true
. - Return undefined if not found.
- f must be a function. The function should return
true
orfalse
.
The function f is passed 3 args:
- currentElement
- currentIndex
- arrayX
- Return the first element of array arrayX where the function f returns
arrayX.find(f , thisArg)
- Use thisArg for this Binding of f
// example of using array.find() const isEven = (x => ( x % 2 === 0 ? true : false ) ) console.log( [7,3,4,2].find (isEven) ); // 4 // if not found, return undefined console.log( [1,3,5].find (isEven) ); // undefined
Here is example using 2nd argument of predicate.
// get the first even value whose index is also even const bothEven = ((x,i) => ( x % 2 === 0 && i % 2 === 0? true : false ) ); console.log( [7,2,4,3].find (bothEven) ); // 4