Using Javascript to Retrieve Object-Related Information from an Associative Array

I have a list of students' names along with the grades they achieved for the semester. How can I modify my JavaScript code to display the first names of students who earned an "A" grade based on the array provided? This is my current progress, but I know it needs improvement.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
    <script>
    var grades= [];

    grades [0] = "F";
    student [0] = "John";
    grades [1] = "D";
    student [1] = "George";
    grades [2] = "C";
    student [2] = "Bill";
    grades [3] = "B";
    student [3] = "Ted";
    grades [4] = "A";
    student [4] = "Rick";

    function getNames ()
    {

        for (var i =0;i <grades.length;i++)
            {
        if (grades[1] = "F")
            {
            document.getElementById("lowgrade").innerHTML= student[1];
            }
        else if(grades[1] = "D")
            {
            document.getElementById("midlowgrade").innerHTML= student[1];
            }
        else if(grades[1] = "C")
            {
            document.getElementById("midgrade").innerHTML= student[1];
            }
        else if(grades[1] = "B")
            {
            document.getElementById("highgrade").innerHTML= student[1];
            }
        else if(grades[1] = "A")
            {
            document.getElementById("bestgrade").innerHTML = student[1];
            }

    }

    </script>

</head>

<body>
    <h1>Grade Checker</h1>
    <form name = "f1">
    Enter Grade<input type ="text" id="grades" name="wed" value="" /><br/>
    <input type="button" value="Check Student" onclick="getNames()" />
    </form>
    <div id="text" />

</body>

</html>

Answer №1

function filterStudentsByGrade(grade){
var grade_students = [];

for(var i=0;i < total_students.length;i++){
if(student_grades[i] == grade){
grade_students.push(total_students[i]);
}
}
return grade_students;
}

var grade_a_students_list = filterStudentsByGrade("A");

Answer №2

function displayStudents(){
  for(var j = 0; j < grades.length; j++){
    if(grades[j] == "F"){
      document.getElementById("lowgrade").innerHTML = student[j];
    }
    else if(grades[j] == "D"){
      document.getElementById("midlowgrade").innerHTML = student[j];
    }
    else if(grades[j] == "C"){
      document.getElementById("midgrade").innerHTML = student[j];
    }
    else if(grades[j] == "B"){
      document.getElementById("highgrade").innerHTML = student[j];
    }
    else if(grades[j] == "A"){
      document.getElementById("bestgrade").innerHTML = student[j];
    }
  }
}

Here are some corrections for your code:

  1. You used j instead of i.
  2. You used == instead of =.
  3. You forgot to close the for loop with }.
  4. Your indentation is incorrect.

Answer №3

var pupils = [
  {name: "Alice", grade: "B"},
  {name: "Bob", grade: "C"}
] //fill in the remaining students

function getStudentsByGradePoints(points){
  return pupils.filter(function(pupil){
    return pupil.grade.toUpperCase() == points.toUpperCase();
  });
});

As = getStudentsByGradePoints('B');
Bs = getStudentsByGradePoints('C');

(and so forth)

or maybe something like this:

['A', 'B', 'C', 'D', 'F'].map(function(grade){
  return pupils.filter(function(pupil){
     return pupil.grade.toUpperCase() == grade; 
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The admin-ajax.php file in WordPress consistently fails to return any value other than

I developed a WordPress ajax plugin, but I am facing an issue where admin-ajax.php always returns 0 and the plugin doesn't work as expected. Here is the code I have implemented: add_action( 'wp_ajax_example_ajax_request', 'example_aja ...

What is the method for determining the required or imported base path?

My package.json includes the main option to set the default file for importing like import 'my-index' from 'my-module' However, I would like to break up my-module into separate files so developers can include them individually with sta ...

Perform a function in jQuery only after the previous one has finished running in a cascading manner

Looking for guidance from an expert on how to accomplish this task. I have HTML code for a multiple choice question with options A to E: <div id="correct-answer-XXXXX" style="display:none;"></div> <div id="wrong-answer-XXXXX" style="display ...

Automating Image Downloads with Puppeteer by Adding Authentication Query String to Image URL

Attempting to save images stored in a web-space account can be challenging. Accessing the private space with credentials and retrieving the image link using Puppeteer works smoothly. However, when the src attribute of the image includes additional authenti ...

Tips for transferring data from one asynchronous function to another in AngularJS

How to transfer a global variable value between two Angular functions? Here are the two global variables: $scope.genewtId = null; $scope.data1 = null; The two Angular functions in question are: $scope.getID = function() { Service1.getId("abc").then(f ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

tips for enabling communication between the server and client

As someone who is new to the world of web development, please bear with me as I ask a question out of curiosity. I am wondering if there is a method for the server to push messages to clients. For instance, imagine a client's webpage featuring a news ...

Having issues with Node.js POST requests not functioning properly

Currently diving into learning the MEAN stack and facing a challenge with executing POST requests on the server. Here is a snippet from my server.js script: var express = require('express'); var bodyParser = require('body-parser'); v ...

Removing   from a text node using JavaScript DOM

I am currently working with xhtml in javascript. To retrieve the text content of a div node, I am concatenating the nodeValue from all child nodes where nodeType is Node.TEXT_NODE. However, sometimes the resulting string includes a non-breaking space enti ...

What is causing Mocha.js to be unable to locate the module?

Having trouble with mocha.js not being able to locate my path! Here's the directory structure I have set up for my node course project: ///////Root --package.json --node_modules/ --playground --server -server.js -db -models ...

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

Tips for utilizing an IF statement in a Protractorjs Spec.js document?

I am attempting to execute the spec.js file across multiple browsers using Multicapabilities in conf.js. However, I specifically want a certain line of code to only run for Internet Explorer. I have tried putting this code snippet inside an IF statement w ...

Storing data using mongoose does not alter the existing information

I encountered an issue with my code while trying to update an object fetched from a MongoDB. The object contains a map with an array, and I am pushing new values to that array within the map successfully. However, even though the object itself reflects the ...

React: When mapping an array of state objects, not all states are displayed

I'm encountering an odd problem while using React. I'm currently developing a budget tracking app that includes a total budget, a form to add new expenses, and displaying those expenses with their costs below. The cost of the new expense will als ...

Modify the name of the document

I have a piece of code that retrieves a file from the clipboard and I need to change its name if it is named image.png. Below is the code snippet where I attempt to achieve this: @HostListener('paste', ['$event']) onPaste(e: ClipboardE ...

Issues arise with the functionality of custom jQuery sliders

I'm attempting to create a bootstrap panel slider using my own jQuery code, but it's not functioning as anticipated. My Objective: I have two links for "previous" and "next", and three panels with distinct headings. When the "previous" link is ...

Is it possible to drag the div container in HTML to resize its width from both left to right and right to left?

After posing my initial inquiry, I have devised a resizing function that allows for the expansion of a div's width. When pulling the right edge of the div to resize its width from left to right, is it possible to adjust the direction or how to resize ...

For optimal display on mobile devices, include "width=device-width" in the meta tag "viewport"

Is it necessary to include "width=device-width" in the meta tag named viewport when dealing with mobile phones? I've been attempting to make use of this, but without success: //iPhone Fix jQuery(document).ready(function(){ if (jQuery(window).widt ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Glistening tabPanel and Analytics by Google

I recently completed a comprehensive tutorial here that delves into the intricacies of Google Analytics. Despite grasping the concepts explained in the tutorial, my understanding of jQuery remains at ground zero. In my ShinyApp, I utilize multiple tabPanel ...