问题描述
我编写了这段代码来根据用户输入对列表进行排序,但是如果用户添加了一个包含输入之间空格的输入,那么以下代码无法获取输出,我需要进行哪些更改才能获得正确的输出?我不想删除字符之间的空格。 例如:用户输入是“Man santra”,那么它应该对“Man”列表进行排序
var users = [{
name: 'Devgad Mango'
},{
name: 'Mantra santra'
},{
name: 'Prag Mango'
},{
name: 'Pirate aam Mango'
},{
name: 'Mango raw'
},];
function search(input) {
const matches = [];
const remeinder = [];
users.forEach(user => {
user.name.startsWith(input) ?
matches.push(user) :
remeinder.push(user);
});
console.log(matches,remeinder)
// Now we sort the matches
matches.sort((a,b) => {
const aa = a.name.toLowerCase();
const bb = b.name.toLowerCase();
if (aa < bb) {
return -1;
}
if (aa > bb) {
return 1;
}
return 0;
});
console.log(matches);
// Now we want to push the remeinders to the end of the sorted array.
matches.push(...remeinder);
console.log(matches);
console.log(input);
}
const str = "*-*+&^%$#@!/\Man santra*";
var output = (str.replace(/[\/\\#@^!,+()&$~%.'":;*?`<>{}-]/g,""));
search(output);
解决方法
您必须使用 user.name.includes() 来检查名称是否存在于变量中。然后您不必删除空格。您只需在搜索函数中传递输入,它就会返回包含该词的匹配项。
var users = [{
name: 'Devgad Mango'
},{
name: 'Mantra santra'
},{
name: 'Prag Mango'
},{
name: 'Pirate aam Mango'
},{
name: 'Mango raw'
},];
function search(input) {
const matches = [];
const remeinder = [];
users.forEach(user => {
user.name.includes(input) ?
matches.push(user) :
remeinder.push(user);
});
// now we sort the matches
matches.sort((a,b) => {
const aa = a.name.toLowerCase();
const bb = b.name.toLowerCase();
if (aa < bb) {
return -1;
}
if (aa > bb) {
return 1;
}
return 0;
});
console.log(matches);
// now we want to push the remeinders to the end of the sorted array.
matches.push(...remeinder);
console.log(matches);
}
const str = "Mango";
search(str);