In this section, we will learn what the find() method is in JavaScript and how to use it.
JavaScript Arrays find() Method: Find Element in Array
Sometimes in an array we’re looking for an element that it matches a set of conditions.
For example, we want to find the first value in an array that is greater than the value 18! We don’t care if the value is 19 or 100, etc. all we care is that the value should be above 18.
This is where we can use the Array `find()` method.
Basically, the `find()` method is used to look for an element in an array that fits a certain condition.
Note: we define the conditions as well for the find() method.
Array find() Syntax:
array.find(function(currentValue, index, arr),thisValue)
Array find() Method Parameters:
The `find()` method takes two arguments.
The first argument is a reference to a function. For each element in the target array, the find method will call the reference function until one of those elements fits the criteria.
This function takes 3 arguments:
- The first argument is the element in the array.
- The second argument is the index of that element.
- The third argument is a reference to the target array.
Inside this function, we specify a set of instructions that will be executed for each element in the array and at the end will return either `true` or `false`. As long as the result of this function is `false` the `find() `method will put the next element of the array as the argument to the function and run the body of the function for it.
But the moment the result of the function becomes true, the `find()` method will return the value that caused the result `true` and won’t call the function anymore.
Other than the function, the `find()` method takes a second argument as well. This second argument, which is optional, is a reference to an object that will bind to the `this` keyword in the target function that we passed as the first argument.
Array find() Method Return Value:
The return value of the `find()` method is an element in the array that passed the test and matched the needs.
Note: if the type of the value that we’re looking for is not in the target array, the return value of this call will be `undefined`.
Example: JavaScript find in array
const arr = [23,4,3,23,4,2,32,5,3,23,423,234,2,3,2423,42]; function eve(value, index, arr){ return value >=100?true: false; } const final = arr.find(eve); console.log(final);
Output:
423
In this example, we’re looking for the first element in the array that is greater than the value of 100.
Here, the first occurrence of an element greater than 100 is 423 and so the engine returned this value as the final value of the call to the `find()` method.
Example: JavaScript search array
const obj1 = { name: "John", age: 1000 } const obj2 = { name: "Omid", age: 29 } const obj3 = { name : "Jack", age :52 } const arr = [obj1,obj2,obj3]; function eve(value, index, arr){ return value.age >=50?true: false; } const final = arr.find(eve); console.log(final.name);
Output:
John