.Find method  in JavaScript

.Find method in JavaScript

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 new array, without changing the given parameter Array.

Syntax

arr.find(callback(currentValue), thisArg)

Let’s see an example of Why FIND is used:

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 each array[i] value and push it in a new variable array with adding it in result.

for(let i = 0;i<array.length ; i++){
    if(array[i] > 15){
        console.log(array[i])
    }
}        

  • Above Example, here for finding Number greater than 15 and element number from array. We used for loop to iterate in each and given an if condition to pass through it and return the true
  • But coder becomes efficient, when he solves the problem in 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!!!!

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 as Array.
  • Then. map takes the action of For loop and takes Array[i] as an argument with name num.
  • And then call back of function continues and gives the result.

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 Find method

  • . find inbuilt Function accepts only function.
  • Either write the function on the same pace or just create a function and call back it 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 condition is not satisfied.
  • Not changes original array.
  • In objects, takes list of objects and destruct the object in function and use. find

💡 Can we use the objects????

Yes!!! we can but objects should be encased within the List!

To view or add a comment, sign in

More articles by G Shabrez

Insights from the community

Others also viewed

Explore topics