Let’s start with .find inBuilt function.
The
find ()
method is used to iterate through the array and complete the find conditioned function by creating a new array, without changing the given parameter Array*//Syntax
arr.find(callback(currentValue), thisArg)
*
Let’s see an example of Why FIND is used:
// // Find the number greater than 18
let array = [10, 8, 15, 18, 9]
let result = []
for(let i = 0;i<array.length ; i++){
if(array[i] > 15){
console.log(array[i])
}
}
// output = 18
Explanation of code
Let’s take the
array with 4 Elements
//Here is an Array let array = [10, 8 15 18, 9]
Then Again
FOR Loop
, which iterates through the array and takes eacharray[i]
value and push it into a new variable array by adding it to the result.for(let i = 0;i<array.length ; i++){ if(array[i] > 15){ console.log(array[i]) } }
Above Example, Here for finding Numbers greater than 15 and element numbers from an array. We used for loop to iterate in each and gave an if condition to pass through it and return the true
But the coder becomes efficient when he solves the problem in a shorter and smart way
so, just can't we do it better? YES OR NO!!!!!
💡 YES!!!!! For better use and efficient work , Find was made as inBuilt function. So, let’s see What it is!!!!
// // Find the number greater than 18
let array = [10, 8, 15, 18, 9]
const findTheNum = (array) =>array.find(num => num > 15)
console.log(findTheNum(array))
// output = 18
Explanation of code
Let’s take the
array with 4 Elements
//Here is an Array let array = [10, 8, 15, 18, 9]
When we use the find function,
We take a new variable function with
Const
then we pass the argument asArray
.Then
.map
takes the action ofFor
loop and takesArray[i] as an argument with name num
And then
call back of function
continues and gives theresult
const findTheNum = (array) =>array.find(num => num > 15)
console.log(findTheNum(array))
// output = 18
💡 YES!!!!! Just in one line, we have finished the array problem. By using FIND Function
Key points of the Find method
.find inBuilt Function accepts only function.
Either write the function at the same pace or just create a function and call back it from .find
This method accepts two parameters
function(currentValue, index, arr)
currentValue: It is a required parameter and it holds the value of the current element.
index: It is an optional parameter and it holds the index of the current element.
arr: It is an optional parameter and it holds the array.
Returns only 1 element as output when the condition is satisfied
returns undefined when the array is empty or the condition is not satisfied
Not changes the original array
In objects, takes a list of objects and destruct the object in function and use .find
💡 Can we use the objects????
Yes!!! we can but objects should be encoded within the List