What is the best way to find the maximum and minimum values within a JSON object that is populated from user inputs using only JavaScript?

Here is a simple form that stores data at the following link: https://jsfiddle.net/andresmcio/vLp84acv/

var _newStudent = {
        "code": code,
        "names": names,
        "grade": grades,
    };

I'm struggling to retrieve the highest and lowest grade with their respective buttons, as it currently shows the last entry as both the maximum and minimum value.

If anyone could provide assistance, I would greatly appreciate it. Please note that the solution should be displayed as is (using alerts) and must only use pure JavaScript, without any jQuery or other libraries.

Thank you in advance.

Answer №1

It seems like there are a couple of issues with your functions. 1.) You keep resetting the variables used to store information in each loop iteration. 2.) You are only comparing each student to themselves in every iteration. To address these concerns, consider the revised code below:

function findHighestGrade(json) {
    if (json.length > 1) {
        var result = "";
        var highestGrade = 0;
        var currentGrade = 0;
        for (var i = 0; i < json.length; i++) {
            currentGrade = parseFloat(json[i].grade);
            if (highestGrade < currentGrade)) {
                highestGrade = currentGrade;
                result = json[i].name + " has the highest grade of " + json[i].grade;
            }
        }
        alert("The highest grade is: " + result);
    } else {
        alert("Please enroll at least two students");
    }
}

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

Is there a way to plot countries onto a ThreeJS Sphere?

Currently engaged in a project involving a 3D representation of Earth. Successfully created a 3D Sphere using ThreeJS ...

Is your script tag not functioning properly with Promises?

Below is the code snippet used to dynamically append scripts in the DOM using promises. This piece of code is executed within an iframe for A-frame technology and it is generated using Google Blockly (Block-based coding). export const appendScript = asy ...

Having trouble accessing an injector service within the promise of a dynamically loaded JavaScript function that has been assigned to a global variable

Query I am facing an issue while trying to integrate PayPal with Angular. I am encountering difficulties when attempting to call an injected service inside a function of the promise returned. Any assistance in resolving this would be greatly appreciated. ...

Switch between Fixed and Relative positions as you scroll

Just a small adjustment is needed to get it working... I need to toggle between fixed and relative positioning. JSFiddle Link $(window).on('scroll', function() { ($(window).scrollTop() > 50) ? ($('.me').addClass('fix ...

Guidelines for incorporating Context API in Material UI

Currently, I am encountering a TypeScript error while attempting to pass a property using the Context API within my components. Specifically, the error message reads: "Property 'value' does not exist on type 'String'" To provide conte ...

Switching from using a computed property in Vue 2 to implementing the Vue 3 Composition API

I am currently in the process of updating my Vue 2 application to Vue 3 and I have been exploring how to work with computed properties using the Composition API in Vue 3. One particular challenge I am facing is migrating a Vue 2 computed property that pro ...

What is the best way to trigger a function once another one has finished executing?

After opening the modal, I am creating some functions. The RefreshBirths() function requires the motherId and fatherId which are obtained from the getDictionaryMother() and getDictionaryFather() functions (these display my mothers and fathers on the page s ...

The conversion of a map to a list is resulting in a null jolt output

I am looking to clean up the transformed JSON by removing any null values using a Jolt spec. Here is an example: Original JSON { "ratings": { "primary": 5, "quality": 4, "design": 5 } } Jolt specifi ...

The React input field seems to be unresponsive to updates

I'm working on a React/Next application where users can create and update notes/jobs. However, I am facing an issue with my onChange={handleChange} function when trying to edit the input fields. Can anyone point out what might be going wrong? Thank y ...

Can you please explain the meaning of this wildcard symbol?

We recently came across a part of our grunt file that was written by a former colleague. While the code functions correctly, the specific purpose of one segment remains a mystery to us! Here is the enigmatic code snippet: dist: { files: [{ ex ...

A guide on combining two similar entities in Laravel

I require assistance with merging two similar objects into one object in Laravel. How can this be achieved? Below are the objects: {"course_code":"UGRC110","venue_id":22,"exam_date":"May 6, 2017","exam_time":"3:30 pm","student_no":400} and {"course_co ...

Is the this.props.onChange method called within the render function?

I'm having trouble grasping the concept of the assigned onChange property in this TextField component I found in the material-ui library: <TextField style = {{"padding":"10px","width":"100%"}} type = {'number'} valu ...

Converting Enum Flags to a String Array in C# using Json.NET

Within a .NET Application, there exists a collection of values stored using a [Flags] enum. The goal is to serialize these values to JSON format, but with a twist; instead of converting the result to an integer, the desired outcome is an array of strings r ...

Looking for nested objects within an array in JavaScript

Currently, I am dealing with a REST API that provides data in the following format: students = [{ batch_id: 22 id: 1 image: null name: "a new batch student", attendance: [ { id: 1, student_id: 1, batch_id: 22, absent_on: "2019-09-15", ti ...

Enhancing Functionality: JavaScript customization of jQuery (or any other object's) function

Within this jsfiddle, the author has created a test for a custom knockout binding. A key aspect of the test involves extending jQuery. My question pertains to lines 30. $.fn.on = function(event, callback) { where it appears that any existing definition o ...

Embedding JSON data in a GSP page

My goal is to transfer JSON data to a GSP page and present it in a table format. The expected JSON structure: { "data": [ [ "Tiger Nixon", "System Architect", "Edinburgh" ] ]} I attempted to achieve this with the following co ...

What is the best way to prevent a directory from being included in the Webpack bundle?

Issue: Despite configuring my Webpack settings in webpack.config.js to exclude files from the ./src/Portfolio directory, all files are being bundled by Webpack. Code Snippet: Webpack.config.js const path = require('path'); module.exports = { ...

Is there a way to determine if a website is utilizing javascript?

Currently, I am in the process of developing a web scraping tool using beautifulsoup. Some of the websites I am targeting contain JavaScript elements that prevent me from using urllib3 efficiently. As a workaround, I have incorporated selenium into my sc ...

Having trouble locating the objects in the parent scope of an Angular directive

My custom directive needs to access the object $scope.$parent.users. When I use console.log $scope.$parent: myDirective.directive('scheduleItem', function(){ return { restrict: 'EA', link: function($sco ...

"Encountering Issues with Angular's Modules and EntryComponents during Lazy Loading

Upon lazy loading an Angular module, I encountered an issue when trying to open my DatesModal that resulted in the following error: No component factory found for DatesModal. Have you included it in @NgModule.entryComponents? The declaration and entryCom ...