javascript - Create an if condition dynamically -
i have following array , created function return items array based on 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 = []; (var = 0; < 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 long pass single filter. if want pass 2 filters, e.g., getgrades(["e", 3], ["b1", 2])
won't work.
i need way configure (extend) if condition students[i][arguments[0][1]] == arguments[0][0]
based on 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 dynamically create if condition?
rather trying dynamically create if
condition, can iterate through each of arguments , check them individually. if 1 of them fails, fail. likewise, if none of them fails, know total result valid.
for (var = 0; < students.length; i++) { var student = students[i]; var matched = true; // won't change if of conditions pass (var j = 0; j < arguments.length; j++) { var filter = arguments[j]; if (student[filter[1]] !== filter[0]) { matched = false; // 1 of conditions failed, don't check rest break; } } if (matched) { grades.push(student[1]); } }
Comments
Post a Comment