jeudi 21 avril 2016

Create an if condition dynamically

I have the following array and I created a function to return items from the array based on the passed filter.

var students = [
    //name      grade   room        gender
    ["name1",   80,     "Farabi",   "K"],
    ["name2",   73,     "B1",       "K"],
    ["name3",   73,     "B1",       "K"],
    ["name4",   60,     "Farabi",   "K"],
    ["name5",   80,     "B1",       "E"],
    ["name6",   43,     "Farabi",   "E"],
];

function getGrades() {
    var grades = [];
    for (var i = 0; i < students.length; i++) {
        if (students[i][arguments[0][1]] == arguments[0][0]) {
            grades.push(students[i][1]);
        }
    }
    return grades;
}

getGrades(["E", 3]); // [gender, column index]

This works as long as I pass a single filter. If I want to pass two filters, e.g., getGrades(["E", 3], ["B1", 2]) it won't work.

I need a way to configure (extend) the if condition students[i][arguments[0][1]] == arguments[0][0] based on the passed arguments.

For getGrades(["E", 3], ["B1", 2]), if condition should be

students[i][arguments[0][1]] == arguments[0][0] && students[i][arguments[1][1]] == arguments[1][0]

How can I dynamically create an if condition?

Aucun commentaire:

Enregistrer un commentaire