我使用了以下过滤功能
$.each(contacts,function(i,contact){
var keyword = (contact.dept+';'+contact.name+';'+contact.location+';'+contact.extn).toLowerCase();
if( keyword.indexOf(newSearchValue) != -1){
newdata.push(contact);
}
});
它的工作正常。它默认按升序过滤。但我确实需要我想要搜索的应该是最重要的,其余的在下面。我怎样才能得到这个结果?
答案 0 :(得分:2)
创建newdata
数组后。你需要像这样排序数组
$.each(contacts, function(i, contact) {
var keyword = (contact.dept + ';' + contact.name + ';' + contact.location + ';' + contact.extn).toLowerCase();
if (keyword.indexOf(newSearchValue) != -1) {
newdata.push(contact);
}
});
newdata =newdata.sort(function(a, b){
return b.indexOf(newSearchValue) - a.indexOf(newSearchValue);
})
示例强>
<强>更新强>
var newdata = [{ "id": "86", "name": "fgdf", "password": "", "dept": "test", "extn": "534534", "mobile_no": "97767867677", "location": "xxxx", "email": "xxxx@gmail.commn", "type": "0", "dept_id": "1",
"created_on": "2017-06-30 11:19:03", "loc_id": "3"}, { "id": "85",
"name": "new", "password": "", "dept": "test1", "extn": "565",
"mobile_no": "4357347853945", "location": "yyyyy", "email": "test@gmail.com", "type": "0", "dept_id": "3", "created_on": "2017-06-30 11:19:03", "loc_id": "3"}]
var newSearchValue = 'h';//change the as your wish
newdata = newdata.sort(function(a, b) {
var a1 = (a.dept + ';' + a.name + ';' + a.location + ';' + a.extn).toLowerCase()
var b1 = (b.dept + ';' + b.name + ';' + b.location + ';' + a.extn).toLowerCase()
return b1.indexOf(newSearchValue) - a1.indexOf(newSearchValue);
})
console.log(newdata)
答案 1 :(得分:0)
这是关于如何设置newdata
数组的问题:
var newdata=['newSearchValue'];
// then put your code snippet here
这样,您的结果数组就会从搜索表达式本身开始,然后是实际的搜索结果。