我正在尝试生成关键字来搜索和显示数据库中的一些内容。我已经给出了一个示例搜索文本和关键字,我想从关键字中派生。有人能指导我如何实现如下所示的从动态搜索字符串中获取关键字的逻辑吗?
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'
}
使用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)
const keywords = searchText.split(' ');
const phrases = [];
for(let length = keywords.length; length > 0; length--) {
phrases.push(keywords.slice(0, length).join(' '));
}
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"
// }