Samuel Tang
Samuel Tang

Reputation: 71

Searching through Array in javascript based on user input

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);
    }
}

Upvotes: 1

Views: 354

Answers (1)

Poojan
Poojan

Reputation: 146

You need to fix these:

  1. Replace for (let i = 0; i <= studentList.length; i++) { with for (let i = 0; i < studentList.length; i++) { so it does not try to access a non-existent index. e.g. if studentList is an array of length 4, the indexes only go from 0 to 3
  2. Change if (studentList[i] == searchName) { to if (studentList[i].name == searchName) {. Otherwise you are comparing an object with a string.
  3. What your code does is it loops through all elements in the studentList and for every entry that is not the searchName, it prints 'student not found'. You only want to print 'student not found' after you have looped through all the list items.
  4. If do you find the student you were finding for, exit the function early with a return keyword.

So your code should look like this:

function searchStudent(searchName) {
  for (let i = 0; i < studentList.length; i++) {
    if (studentList[i].name == searchName) {
      console.log(studentList[i]);
      return;
    }
  }
  console.log('student not found');
}

Here is another way of doing the same thing:

function searchStudent(searchName) {
  const student = studentList.find(student => student.name === searchName);
  if (!student) {
    console.log('student not found');
    return;
  }
  console.log(student);
}

Upvotes: 1

Related Questions