0

My sorting function at the end isn't working. I want to sort student grades in ascending order but I can't get it to print out. My sorting function goes through and manually compares however I can't get it to work. The problem may be that the student class is whats being used to add values to the array.

<html>
<body>
<script>
    class Student {
        constructor(name,grade) {
            this.name = name;
            this.grade = grade;
        }
         detail() {
            document.writeln(this.name + " " + this.grade + "<br/>")
         }
    }
    var grade = [];
    var count = 0;

    function setStudent() {
        var name = prompt("Enter Name", "name");
        while(name != '???') {
                var grades= parseInt(prompt("Enter Grade", "Grade"));
                var student = new Student(name,grades);
                grade.push(student);
                name = prompt("Enter Name", "name");
                count++
                }
        }

    function showGrades() {
        for(i=0;i<count;i++) {
            grade[i].detail();
        }
    }
    function maxGrade() {
        var mgrade = grade[0].grade;
        var names = "";
        for (i=0;i<count;i++) {
            if(mgrade<grade[i].grade) {
                mgrade=grade[i].grade;
                names = grade[i].name
            }
        }
        document.writeln("Max Grade: " + mgrade + " Name: " + names);
    }

    setStudent();
    showGrades();
    maxGrade(); 
    document.writeln("<br/> Assorted List (Ascending): <br/>"); 

    grade.sort(function(a,b) {
        return a[0] - b[0] || a[1] - b[1];
    });
    console.log(grade);



</script>
</body>
</html>
  • 2
    Possible duplicate of [How to sort 2 dimensional array by column value?](https://stackoverflow.com/questions/16096872/how-to-sort-2-dimensional-array-by-column-value) – Taki Sep 26 '19 at 17:27
  • When you say you can't get it to work what do you mean? It throws an error? It sorts the data but not the way you want? – luis.parravicini Sep 26 '19 at 18:41

1 Answers1

0

The problem is this statement:

 grade.sort(function(a,b) {
        return a[0] - b[0] || a[1] - b[1];
    });

a and b are Student objects. It shows that right in your console.log statement. So, a[0] and b[0] are undefined.

I am not sure what a[1] - b[1] refers to, but I think you want this:

grade.sort(function(a,b) {
        return a.grade - b.grade;
    });
Mike Furlender
  • 3,869
  • 5
  • 47
  • 75