[英]Derive keywords from search text
我正在尝试生成关键字来搜索和显示数据库中的一些内容。我给出了一个示例搜索文本和我想从关键字中派生的关键字。 有人可以指导我如何实现从动态搜索字符串中获取关键字的逻辑,如下所示?
var searchText='My name is John santose mayer'
var Keywords={
1: 'My name is John santose mayer',
2: 'My name is johns santose',
3: 'My name is John',
4: 'My name is',
5: 'My name'
6: 'My'
}
const keywords = searchText.split(' ');
const phrases = [];
for(let length = keywords.length; length > 0; length--) {
phrases.push(keywords.slice(0, length).join(' '));
}
像这样使用reduce
?
var searchText='My name is John santose mayer'; let keywords = searchText.split(' ').reduce((prev, next) => { const concatWith = prev[prev.length - 1]? prev[prev.length - 1] + ' ': '' return [...prev, concatWith + next] }, []).reverse() console.log(keywords)
split
, map
, slice
和reduce
的简单组合应该可以解决问题。
const foo = "My name is John santose mayer"
.split(" ")
.map<string>((_, i, arr) => arr.slice(0, arr.length - i).join(" "))
// [
// "My name is John santose mayer",
// "My name is John santose",
// "My name is John",
// "My name is",
// "My name",
// "My"
// ]
.reduce<{ [key: number]: string }>((acc, curr, i) => {
acc[i + 1] = curr;
return acc;
}, {});
console.log(foo);
// {
// "1": "My name is John santose mayer",
// "2": "My name is John santose",
// "3": "My name is John",
// "4": "My name is",
// "5": "My name",
// "6": "My"
// }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.