javascriptarraysloops

How can I output data from a nested array in JavaScript?


I created a multidimensional array:

var students = [ [['David'], [80]], [['Vinoth'], [77]], [['Goren'],[55]] ];  

Then I created an if statement that will test if the student's grade is F to A.

for (var i = 0; i < students.length; i++) {
    for (var j = 1; j < students.length; j++) {
        document.write(students[i][j] + "<br/>");

        if (students[i][j] < 60) {
            document.write(students[i][j] + " is Grade : F");
        } else if (students[i][j] < 70) {
            document.write(students[i][j] + " is Grade : D");
        } else if (students[i][j] < 80) {
            document.write(students[i][j] + " is Grade : C");
        } else if (students[i][j] < 90) {
            document.write(students[i][j] + " is Grade : B");
        } else if (students[i][j] < 100) {
            document.write(students[i][j] + " is  Grade : A");
        }
    }
}

In my pursuit to output the name of the student and the grade, I even ended up creating three for loops, which did not work.

I was wondering how can I achieve this output:

David's grade is 80 and is C Grade.
Vinoth's grade is 77 and is C Grade.
Goren's grade is 55 and is F Grade.

What am I missing?


Solution

  • Other answers have suggested simplifying your array structure. If you really want to use your extra nesting, you need to do an extra level of indexing. But you don't need nested loops, because it's still just a linear structure.

    for (var i = 0; i < students.length; i++) {
        var student = students[i][0][0];
        var score = students[i][1][0];
        var grade;
        if (score < 60) {
          grade = "F";
        } else if (score < 70) {
          grade = "D";
        } else if (score < 80) {
          grade = "C";
        } else if (score < 90) {
          grade = "B";
        } else if (score < 100) {
          grade = "A";
        }
        document.write(student + "'s score is " + score + ' and is Grade ' + grade + '<br>');
    }
    

    Also, if you expect a score of 80 to generate a C grade rather than B, you should be using <= rather than < in the comparisons.

    As a general rule, I recommend using objects rather than arrays for heterogeneous data, so your array should be like:

    var students = [ {
        name: 'David',
        score: 80
    }, {
        name: 'Vinoth',
        score: 77
    }, {
        name: 'Goren',
        score: 55
    }];
    

    Then you use students[i].name and students[i].score, which is much easier to understand.

    The idea is that you use arrays for collections of things that are all the same type, and objects for collections of related information about a thing.