Reputation: 12027
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?
Upvotes: 0
Views: 4889
Reputation: 731
An alternate getGrades
implementation using Functional Programming
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 filters = Array.prototype.slice.call(arguments); //converts all passed filters to array
return filters.reduce(function(result,filter){ //result is filtered student list till now
return result.filter(function(student){ //return new filtered list
return student[filter[1]] === filter[0];
});
},students).map(function(student){ //map filtered students to their grades
return student[1];
})
}
document.write(getGrades(["E", 3], ["B1", 2]));
Upvotes: 0
Reputation: 32511
Rather than trying to dynamically create an if
condition, you can iterate through each of the arguments and check them individually. If one of them fails, they all fail. Likewise, if none of them fails, you know that the total result is valid.
for (var i = 0; i < students.length; i++) {
var student = students[i];
var matched = true; // This won't change if all of the conditions pass
for (var j = 0; j < arguments.length; j++) {
var filter = arguments[j];
if (student[filter[1]] !== filter[0]) {
matched = false; // One of the conditions failed, don't check the rest
break;
}
}
if (matched) {
grades.push(student[1]);
}
}
Upvotes: 1