请原谅标题,但基本上这是我想要做的:
我有一个对象数组,在本例中,我们称它们为狗。每个对象看起来像这样:
{
name: "Poodle",
keywords: ["Fluffy", "Intelligent", "Hypo-allergenic", "Loyal"]
}
用户选择三个单词,然后我要搜索对象数组,并将这三个单词与每个数组的'keywords'属性进行匹配。然后我有一些显示逻辑:
[基本上,我不是问如何做要点,我可以弄清楚这一点,但理想情况下,我需要一排狗,每只狗旁边都要有一些火柴。然后,我可以对此进行一些过滤。
所以我需要一个狗名数组,总共要匹配,像这样(当然,除非有更好的方法,否则我全是耳朵):
[
["Poodle", 2],
["Labrador", 2],
["Schpitz", 1],
["Setter", 0],
["Pit Bull", 0]
]
这听起来是最好的方法,还是有一种更简单/更好的方法?
在这里,您找到了所有匹配关键字的狗狗。
您可以轻松地从中获得匹配的关键字数量,但是我认为这更实用,因为您还可以显示实际匹配的关键字。
const data = [
{
name: "Poodle",
keywords: ["Fluffy", "Intelligent", "Hypo-allergenic", "Loyal"]
},
{
name: "Husky",
keywords: ["Fluffy", "Cute", "Stuff", "IdkMuchAboutDogs"]
}
];
const keywords = ["Fluffy", "Cute", "Intelligent"];
const result = data.map(dog => {
return {
dog: dog,
matches: keywords.filter(keyword => dog.keywords.indexOf(keyword) !== -1)
};
});
console.log(result);
如果您希望在关键字比较方面有更多逻辑,则需要执行类似操作
...
matches: keywords.filter(keyword =>
dog.keywords.filter(dogkeyword =>
dogkeyword.toLowerCase() == keyword.toLowerCase()
).length !== 0
)
...
或类似。
您可以根据自己的意愿生成分数:
let dogs = [
{
name: "Poodle",
keywords: ["Fluffy", "Intelligent", "Hypo-allergenic", "Loyal"]
},
{
name: "Dog2",
keywords: ["Fluffy", "Intelligent", "Hypo-allergenic",]
},
{
name: "Dog3",
keywords: ["Fluffy"]
}
]
得分:
let scored = words => dogs.map(dog => {
// you can add modification for 2 words term
let score = dog.keywords.filter(kw => words.includes(kw)).length
return {
name: dog.name,
score
}
})
然后按最佳分数排序:
let sorted = dogs => dogs.sort((a,b) => b.score - a.score)
console.log(sorted(scored(['Fluffy', 'Loyal', "Intelligent"])))
{name: "Poodle", score: 3}
{name: "Dog2", score: 2}
{name: "Dog3", score: 1}
这不是最佳选择,但是您可以随时进行修改。