我有一系列对象,如下所示 [{city:&#34; Amsterdam&#34;,country:&#34; Netherlands&#34;},{city:&#34; Norwalk&#34;,country:&#34; United States&#34;}, {city:&#34; Norwalk&#34;,country:&#34; United States&#34;},{city:&#34; Unknown&#34 ;, country:&#34; Unknown&#34;}] < / p>
我想实现对结果进行排序的搜索,以便当用户输入第一个字母时,例如&#34; N&#34;在搜索框中,它应按以下排序顺序显示结果。 A)以&#34; n&#34;开头的城市 B)以&#34; n&#34;开头的国家 C)包含&#34; n&#34;的城市。 D)包含&#34; n&#34;
的国家/地区我试图实现类似这样的东西
filteredData = gridData.filter(function (rowObj) {
if (!!filterText) {
//Filter records with some function.
return isSubstringIgnoreCase(filterText, rowObj.city) || isSubstringIgnoreCase(filterText, rowObj.country);
}
return true;
});
filteredData.sort(function(a,b) {
var cityA = a.city.toLowerCase(),
cityB = b.city.toLowerCase(),
countryA = a.country.toLowerCase(),
countryB = b.country.toLowerCase();
filterText = filterText.toLowerCase();
if(cityA.indexOf(filterText) < cityB.indexOf(filterText) || cityA.indexOf(filterText) < countryB.indexOf(filterText)) {
return -1;
} else if(cityA.indexOf(filterText) > cityB.indexOf(filterText) || cityA.indexOf(filterText) > countryB.indexOf(filterText)) {
return 1;
} else if(countryA.indexOf(filterText) < countryB.indexOf(filterText) || countryA.indexOf(filterText) < cityB.indexOf(filterText)){
return -1;
} else if(countryA.indexOf(filterText) > countryB.indexOf(filterText) || countryA.indexOf(filterText) > cityB.indexOf(filterText)){
return 1;
} else {
return 0;
}
});
但它没有按预期工作。请帮助我解决这个问题。
答案 0 :(得分:1)