背景
我正在尝试使用javascript开发搜索/过滤器算法,而且我很难过。我有一个度数的数组,其中包含度数名称以及与之关联的过滤器。我的filterSearch()函数获取用户从HTML字段中选择的过滤器。 getDept()函数只返回一个部门值,而getSearchValue()返回多选字段中的值。
filterSearch()函数获取用户选择的过滤器,并使用includes方法将其与degrees数组中的过滤器进行比较。如果恰好有一个过滤器不是用户选择的一部分,那么该函数中的两个for循环进行比较并突破循环。如果检查仍然为真,则将其推送到结果数组以输出给用户。
问题
说我选择" Bachelor,Business,Traditional和Main_Campus"作为用户的过滤器,它将第一个度数推送到结果上没有问题,并过滤掉第二个度数。然而!假设我选择" Bachelor,Associate,Business,Traditional和Main_Campus"我希望将第二个学位添加到结果中,但两者都不会被推。我做了一些调试,事实证明它说的是" Bachelor"不包括在第一学位和" Associate"不是第二学位。
我对所有建议和解决方案持开放态度,我非常喜欢一些指导。
var degrees = [
{degree: "Business Administration", filters: "Business Bachelor Traditional Main_Campus"},
{degree: "Applied Science", filters: "Business Associate Online Main_Campus"}
]
function filterSearch(){
var filters = getFilters();
var array = [];
var check = false;
var results = [];
for (var i = 0; i < degrees.length; i++){
array = degrees[i].filters.split(' ');
for (var j = 0; j < array.length; j++){
if (filters.includes(array[j])) { check = true; }
else {
check = false;
break;
}
}
if (check == true) results.push(degrees[i]);
}
}
function getFilters(){
var filters = [];
var d = this.getDeptVal();
var p = this.getSearchValue('#programType');
var f = this.getSearchValue('#formatType');
var l = this.getSearchValue('#locationType');
filters.push(d); filters.push(p); filters.push(f); filters.push(l);
return filters;
}
function getDeptVal(){
var selected = $('#departmentType option:selected').text();
return selected;
}
function getSearchValue(searchId){
var selected = $(searchId).val();
var toString = selected.toString();
return toString;
}
答案 0 :(得分:0)
也许你需要这样一个过滤器:
var degrees = [
{degree: "Business Administration", filters: "Business Bachelor Traditional Main_Campus"},
{degree: "Applied Science", filters: "Business Associate Online Main_Campus"}
];
function get_degrees_by_filters(_filters){
var found=[];
var temp_degrees=degrees.slice(0); //clone original array
var input_filters_arr=_filters.split(' ');
for(var key in temp_degrees){
var degree=temp_degrees[key].degrees;
var filters=temp_degrees[key].filters;
var filters_arr=filters.split(' ');
for(var key_f in filters_arr){
for(var key_if in input_filters_arr){
filter=input_filters_arr[key_if];
if(filters_arr[key_f]==filter){
if(temp_degrees[key]){
found.push(temp_degrees[key]);
delete temp_degrees[key];
}
}
}
}
}
return found;
}
<input type="button" value="filters: Bachelor" onclick="console.log(get_degrees_by_filters('Bachelor'));"/></br>
<input type="button" value="filters: Associate" onclick="console.log(get_degrees_by_filters('Associate'));"/></br>
<input type="button" value="filters: Bachelor Associate" onclick="console.log(get_degrees_by_filters('Bachelor Associate'));"/></br>
<input type="button" value="filters: Associate Online" onclick="console.log(get_degrees_by_filters('Associate Online'));"/></br>