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

Global jQuery variables are unexpectedly coming back as "undefined" despite being declared globally

I need to save a value from a JSON object in a global variable for future use in my code. Despite trying to declare the country variable as global, it seems like it doesn't actually work. $.getJSON(reverseGeoRequestURL, function(reverseGeoResult){ ...

What is the best method for playing raw audio wav files directly in a web browser?

I'm currently attempting to play wav raw data in the browser that is being transmitted from a Node.js server via socket.io. The main goal is to play the receiving data as quickly as possible without waiting for all the data to be received. I initially ...

Incorrectly resolving routes in the generate option of Nuxt JS's .env configuration file

Having trouble using Nuxt JS's 2.9.2 generate object to create dynamic pages as static files by referencing a URL from my .env file: nuxt.config.js require('dotenv').config(); import pkg from './package' import axios from 'a ...

What is the best way to store JSON encoded items in an array using square brackets?

Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue whe ...

Tips for personalizing react-show-more text length with Material-UI Icons

In my SharePoint Framework webpart using React, I am currently utilizing the show more text controller. However, I am interested in replacing the "Show More" and "Show Less" string links with the ExpandMore and ExpandLess Material UI icons. Is there a way ...

Guide on updating a single element in a Firebase array

I have an array stored in my firebase database, structured like this: matches:[ {match:{id:1,data:...}}] I am looking for a way to update just one specific item within this array. Let's say I want to locate the match with the ID of 32 and modify its ...

Sort through each individual column in the table

My table filtering code isn't working, and I need to add a status filter with checkboxes. Can someone guide me on how to proceed? var $rows = $('tbody > tr'), $filters = $('#filter_table input'); $filters.on("keyup", fun ...

Creating a form submission event through Asp.net code behind

Is there a way to change the onsubmit parameter of a form in an asp.net project, specifically from the master page code behind of a child page? I am interested in updating the form value so that it looks like this: <form id="form1" runat="server" onsu ...

Implementing Google Calendar access token in JavaScript: A practical guide

I have a question about Google Calendar and I'm hoping you can assist me. I currently have an access_token from Google Calendar that has been stored in the localStorage. const googleAccessToken = e.vc.access_token; localStorage.s ...

Troubleshooting a Node.js server issue with a two-dimensional array

I am currently facing an issue with submitting a form that contains two-dimensional array fields on a post request in node.js. The problem lies in the fact that the server side is receiving a one-dimensional array with all the values combined. Below is an ...

Struggling to send information using Angular $resource?

I've been working on sending data to an API using Angular's $resource. Currently, I can successfully retrieve data from my test server using a GET request or querying. However, I'm having trouble figuring out how to send new data to the serv ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

Is it possible for me to declare attributes using a function object in a single statement?

Given an object obj, the following two-line statements can be defined: var obj ={} //this is an object obj.isShiny = function () { console.log(this); return "you bet1"; }; These two lines can be combined into a one-line statement ...

In the dragstart event handler, event.dataTransfer and event.originalEvent will consistently be null

I have been working on developing drag and drop directives for angularJS by referencing this informative post: However, I am facing an issue where the dataTransfer and originalEvent are consistently null within the dragstart event handler, preventing me f ...

Footer Section (navigation) bounces up when scrolling to the beginning of the page

I am currently developing a fully web-based app-style layout. One issue I'm facing is that the navigation menu jumps slightly when I use my S3 to auto-scroll to the top by dragging. However, if I scroll up manually without lifting my finger, this pro ...

Using Vue.js along with vuex and axios allows for data retrieval only upon the second load

After creating a Vue.js app with vuex as a central store and using axios for basic API calls, I implemented the following store action: loadConstituencyByAreaCodeAndParliament({commit}, {parliament_id, area_code}) { axios.get('/cc-api/area-code/ ...

Steps to import shared CSS using Styled-components

In my project using react, I've implemented styled-components for styling. One requirement is to have a shared loading background. Here is the code snippet of how I defined it: const loadingAnimation = keyframes` 0% { background-position: 95% 95%; } ...

Tips for avoiding page reload when submitting a form with form.submit() in ReactJs

Is there a way to avoid the page from refreshing when triggering form submission programmatically in ReactJS? I have attempted to use this block of code: const myForm = () => <form onBlur={(e) => { if(!e.relatedTa ...

Creating a toggle feature using ng-switch

I'm having trouble getting this code to function correctly as a toggle. Can anyone offer any suggestions on what might be causing the issue? <div ng-switch="!!myvar"> <a ng-switch-when="false" ng-click="myvar = true" style="cursor:poin ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...