How to create a custom function similar to find() method in JavaScript?



Let’s say we have the following records of studentId and studentName and want to check a specific student name −

const studentDetails= [    {       studentId:101,       studentName:"John"    },    {       studentId:102,       studentName:"David"    },    {       studentId:103,       studentName:"Carol"    } ]

Create a custom function to find by name. Following is the code −

Example

const studentDetails= [    {       studentId:101,       studentName:"John"    },    {       studentId:102,       studentName:"David"    },    {       studentId:103,       studentName:"Carol"    } ] function findByName(name){    var flag=true;    for(var i=0;i<studentDetails.length;i++){       if(studentDetails[i].studentName==name){          flag=true;          break       } else{          flag=false;       }    }    if(flag==true){       console.log("The name found="+name);    } else{       console.log("The name not found="+name);    } } findByName("David");

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo106.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo106.js The name found=David
Updated on: 2020-09-09T12:56:13+05:30

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements