Hey guys im trying to search through an array and display the search results base on the user input
A runthrough of my program is to read in an array of student name and their marks and determine their grades. Afterwhich, I want to search for a student and display his name, mark and grades.
Currently what I have so far is always printing student not found.
"use strict"
const readline = require('readline-sync');
var name, marks;
var studentList = [];
input();
search();
function printList(list) {
for (const entry of list) {
// Get a local for `marks` via destructuring
const {marks} = entry;
if (marks > 100 || marks < 0) {
throw new Error(`Invalid 'marks' value: ${marks}`);
} else if (marks >= 80) {
entry.grade = 'HD'
} else if (marks >= 70) {
entry.grade = 'D'
} else if (marks >= 60) {
entry.grade = 'C'
} else if (marks >= 51) {
entry.grade = 'P'
} else { // No `if (marks >= 0)` because we know it is, otherwise we would have thrown an error above
entry.grade = 'N'
}
console.log(entry);
}
function searchStudent(searchName){
for (let i = 0; i<= studentList.length; i++){
if(studentList[i] == searchName){
console.log(studentList[i]);
}
else {
console.log("student not found");
}
}
}
function input() {
while (true)
{
console.log('Please enter the student name (or "end" to end): ');
const name = readline.question('Student Name: ');
if (name === 'end')
{
printList(studentList);
break;
}
console.log('Student Name is' , name);
const marks = readline.question('Enter marks for ' + name + ': ');
if (marks === 'end')
{
printList(studentList);
break;
}
console.log('Marks for ' + name + ' are ' + marks );
studentList.push({name:name, marks: parseFloat(marks)});
}
}
function search() {
while (true)
{
console.log('Please enter the name of student to search for: (or "stop" to end search): ');
const searchName= readline.question("Student Name: ");
if(searchName === 'stop'){
break;
}
searchStudent(searchName);
}
}
for (let i = 0; i<= studentList.length; i++)withfor (let i = 0; i< studentList.length; i++)studentList.push({name:name, marks: parseFloat(marks)}), but searchName is a string. I think you want to changeif(studentList[i] == searchName)toif(studentList[i].name == searchName)