0

as you may see over the link (https://jsfiddle.net/andresmcio/vLp84acv/) is a simple form that stores data as:

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

I'm having trouble getting the highest and lowest grade with their respective buttons as it is showing the last entry as either maximum and minimum value.

Would be glad if anyone could help, keeping in mind that it should be displayed as it is (With the alerts) and only using javascript, not jquery or any other.

Thanks beforehand.

  • You should include the functions that calculate the highest and lowest grades in the question, that way people can directly see and reference your work. – AeroBuffalo Apr 14 '17 at 23:56
  • Welcome to Stack Overflow! Post your code here, not just at a remote site. You can use [Stack Snippets](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) to make it executable. – Barmar Apr 14 '17 at 23:57
  • You need to call `Math.max()` with all the grades, not just one of them. It calculates the max of all its arguments. If you put them in an array, see [here](http://stackoverflow.com/questions/1669190/javascript-min-max-array-values) for how to get the max and min. – Barmar Apr 15 '17 at 00:00

1 Answers1

0

It looks like you might have two problems in your functions. 1.) You are resetting the variables used to track the information with each iteration. 2.) You are only comparing each student to the same student, during each iteration. Thus, I think something like the below would provide what you are looking for.

function hghGrade(json) {
    if (json.length > 1) {
        var text = "";
        var maxGrade = 0;
        var thisGrade = 0;
        for (var i = 0; i < json.length; i++) {
            thisGrade = parseFloat(json[i].grade);
            if (maxGrade < thisGrade)) {
                maxGrade = thisGrade;
                test = json[i].names + " ID code " + json[i].code + " with grade " + json[i].grade;
            }
        }
        alert("The best grade is from: " + text);
    } else {
        alert("Please register at least two students");
    }
}
AeroBuffalo
  • 1,126
  • 1
  • 11
  • 31
  • Perfect @AeroBuffalo !! Just as needed. I did notice the mistake of including the text variable and that it was just applying max to an item but decided to post the original code because other tries returned nothing. Thanks for your help. :) – Andresmcio Apr 15 '17 at 00:52