Ad

Compare Values In Two Arrays

- 1 answer

I have two arrays.

    var letterGrades = ["A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D",  "D-"];
    var fall = ["Fall 2015", "A", "B", "A-"];

What I need to do is compare the two arrays and print out any values that are equal.

This is what I have tried so far...

function getGrades(semester){
if(semester === "Fall 2015"){
    for (var i = 1; i < 5; i++) {            
        for(var x = 0; x < letterGrades.length; x++){
            if(fall.data[0][i] == letterGrades[x]){
               console.log(fall.data[0][i]);
            }
        }
    }
}

getGrades("Fall 2015");

Any suggestions on how to do this? Right now, I am not getting anything returned. Thank you!

Ad

Answer

You're not getting anything returned because there's an error accessing the array fall. It's a 1D array but you're accessing it with fall.data[0][i]. That causes syntax error Uncaught SyntaxError: Unexpected end of input

You can loop through each element in fall starting from index 1 and in every iteration check if the current character is in letterGrades like this:

var letterGrades = ["A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D",  "D-"];
var fall = ["Fall 2015", "A", "B", "A-"];

function getGrades(semester){
    if(semester === "Fall 2015"){
        for (var i = 1; i < fall.length; i++) {            
            if (letterGrades.indexOf(fall[i]) >= 0) {
                console.log(fall[i]);
            }
        }
    }
}

getGrades("Fall 2015");
Ad
source: stackoverflow.com
Ad