Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements