gpt4 book ai didi

javascript - 如何首先渲染搜索到的项目和所有匹配的项目JavaScript?

转载 作者:行者123 更新时间:2023-12-02 22:30:16 24 4
gpt4 key购买 nike

我需要将 John Daniel 渲染在顶部,然后渲染其他匹配的单词

let searchPerson = "John Daniel"
Person = [
"Harry Daniel",
"John Daniel",
"Michael Jackson",
"Anup Jackson",
]
let mySearch = searchPerson.toLowerCase().split(' ')
console.log(Person.filter(string => {
let containsAtLeastOneWord = false;

mySearch.forEach(word => {
if (string.toLowerCase().includes(word))
containsAtLeastOneWord = true;
})
if (containsAtLeastOneWord)
return string
}))

最佳答案

一种简单的方法是考虑匹配的关键字数量,然后将相关的关键字推到顶部,其余的推到最后。您可以尝试以下操作,并根据需要添加其他验证。

let searchPerson = "John Daniel"
Person = [
"Harry Daniel",
"John Daniel",
"Michael Jackson",
"Anup Jackson",
]
let mySearch = searchPerson.toLowerCase().split(' ');
let list = new Array();
let temp = 0;

Person.forEach(name => {
temp = 0;
mySearch.forEach(word => {
if (name.toLowerCase().indexOf(word) >= 0)
temp++;
})
if ( temp > 1 )
list.unshift(name); //Push to the top
else if ( temp == 1 )
list.push(name);
});
console.log("List: " + list);

关于javascript - 如何首先渲染搜索到的项目和所有匹配的项目JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58928083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com