var countries = ["Algeria", "Canada", "Danmark", "Estonia"];
var search = "da";
现在,我希望对该列表进行排序,以便获得以下信息:
sortedCountries === [“ Da nmark”,“ Cana da ”,“阿尔及利亚”,“爱沙尼亚”]
我希望DAnmark在CanaDA之前出现,因为在该字符串的较早位置找到了“ da”。 我不希望按升序/降序进行排序。
答案 0 :(得分:0)
您可以使用Array.prototype.sort
:
var countries = ["Algeria", "Canada", "Danmark", "Estonia"];
var search = "da";
console.log(countries.sort((a, b) => {
a = a.toLowerCase().indexOf(search) + 1
b = b.toLowerCase().indexOf(search) + 1
if(!a && !b) return 0
else if(!a) return 1
else if(!b) return -1
else return a - b
}))
我们也可以将其写为实用函数:
var countries = ["Algeria", "Canada", "Danmark", "Estonia"]
const searchCountries = (a, s) => a.sort((a, b) => {
s = s.toLowerCase()
a = a.toLowerCase().indexOf(s) + 1
b = b.toLowerCase().indexOf(s) + 1
if(!a && !b) return 0 // don't sort if search fails for both
else if(!a) return 1 // swap results since b has a value, but a doesn't
else if(!b) return -1 // leave results since a has a value, but b doesn't
else return a - b // otherwise, sort by indexOf result
})
console.log(searchCountries(countries, 'da'))
console.log(searchCountries(countries, 'a'))
console.log(searchCountries(countries, prompt()))