【发布时间】:2022-09-23 20:59:59
【问题描述】:
我试图检测单词数组中的句子以确定哪些是唯一的。
知道我的函数能够检测句子,但前提是数组中的单词是连续的,例如:
const words: Words[] = [
{ id: 1, content: \"Date\" },
{ id: 2, content: \"of\" },
{ id: 3, content: \"my\" },
{ id: 4, content: \"Birthday\" },
{ id: 5, content: \"Date\" },
{ id: 6, content: \"of\" },
{ id: 7, content: \"his\" },
{ id: 8, content: \"Birthday\" },
];
函数查找文本:
function findText(searchStr: string, words: any[]) {
const cleanEnding = (word: string) => {
return word.replace(/[\\s:;]*$/, \'\');
};
const cleanStart = (word: string) => {
return word.replace(/^[\\s]*/, \'\');
}
const getAliases = (word: string) => {
return [word, word.replace(\'i\', \'1\'), word.replace(\'i\', \'l\')];
};
searchStr = \'\' + cleanEnding(searchStr);
const wordsString: string = words.map((w) => {
w.content = cleanStart(cleanEnding(w.content));
return w.content.toLowerCase()
}).join(\" \");
const splitString = wordsString.split(\" \");
const splitSearch = searchStr.toLowerCase().split(\" \");
let idxs: number[] = [];
splitString.forEach((string, idx) => {
splitSearch.forEach((search) => {
if (string === search) {
const possibleMatch = splitString.slice(
idx,
idx + splitSearch.length,
);
splitSearch.join(\" \") === possibleMatch.join(\" \") && getAliases(possibleMatch.join(\" \").toLowerCase()).includes(splitSearch.join(\" \").toLowerCase()) &&
idxs.push(idx);
}
});
});
const result: any[] = [];
if (idxs.length === 1) {
for (let i = 0; i < splitSearch.length; i++) {
result.push(
words[idxs[0] + i]
);
}
return result;
} else if (idxs.length > 1) {
for (let i = 0; i < idxs.length; i++) {
let sub: any[] = [];
for (let j = 0; j < splitSearch.length; j++) {
sub.push(
words[idxs[i] + j]
);
}
result.push(sub)
}
return result;
} else {
return null;
}
}
const result = findText(\"Date of his\", words) 返回:
[
{ id: 5, content: \'Date\' },
{ id: 6, content: \'of\' },
{ id: 7, content: \"his\" },
]
const result = findText(\"Date of\", words) 返回:
[
[ { id: 1, content: \'Date\' }, { id: 2, content: \'of\' }],
[ { id: 5, content: \'Date\' }, { id: 6, content: \'of\' }],
]
const result = findText(\"Date of abc\", words) 返回:
null
我希望它在给定一个非连续数组时表现相同,关于如何实现这一点的任何想法?
-
听起来你把事情复杂化了。如果您只想检查数组中是否存在单词,您可以在拆分字符串后不使用 Array.find() 或 Array.filter() 助手吗?也许我不明白你想要什么。
-
在数组的上下文中,“连续”与“非连续”是什么意思尚不清楚。所有这些数组中的元素都是连续的,即数组不是稀疏的。目前,我无法判断您关注的问题是数据结构还是数据集。
-
我想我做了你需要的...
-
您确实需要解释“非连续”的含义。
\"Date of\"现在应该返回[[{id: 1,...}, {id: 2,...}], [{id: 1,...}, {id: 6,...}], [{id: 5,...}, {id: 1,...}], [{id: 5,...}, {id: 6,...}]]吗?\"of of of\"会因为列表中只有两个\"of\"而失败吗?这是什么意思?
标签: javascript arrays typescript algorithm