如何从javascript中的对象列表中找到字符串的某些部分与对象的字符串值的最完美匹配?

我在前端 storedList 中有一个列表。我需要检查字符串 str1 的某些部分是否与 storedList 中的 text 参数的任何值完全匹配。 我尝试使用include()并在下面给出了输出。

let storedList = [
    { id: 1,text: 'Higher Education' },{ id: 2,text: 'Higher Education in Physics' },{ id: 3,text: 'Higher Education in Chemistry' },{ id: 4,text: 'Higher Education in Math' },{ id: 5,text: 'Higher Education in Biology' },{ id: 6,text: 'Higher Education in History' },{ id: 7,text: 'Higher Education in Economics' },];

let str1 = 'unnecessay texts Higher Education in Biology unnecessary texts';

for (let row of storedList) {
    console.log(str1.includes(row.text));

    // output
    // true
    // false
    // false
    // false
    // true
    // false
    // false
}

现在我有两个问题。

  1. 我们可以看到,“高等教育”和“生物学高等教育”有两个 true 结果。但是我只想要最后一个,因为它比第一个更准确。该怎么做?
  2. 我的 storedList 列表中最多可以包含60,000个对象。因此,要检查字符串 str1 ,我需要在进程中循环60,000次!还有,如果我必须检查storedList中的1000个不同的字符串怎么办。是60,000 * 1000倍!

真的需要一个更好,更有效的解决方案。

zxbzhangyi 回答:如何从javascript中的对象列表中找到字符串的某些部分与对象的字符串值的最完美匹配?

您可以使用Array.reduce()并使用带有较长文本的对象,该文本也包含在str1中:

const storedList = [
  { id: 1,text: 'Higher Education' },{ id: 2,text: 'Higher Education in Physics' },{ id: 3,text: 'Higher Education in Chemistry' },{ id: 4,text: 'Higher Education in Math' },{ id: 5,text: 'Higher Education in Biology' },{ id: 6,text: 'Higher Education in History' },{ id: 7,text: 'Higher Education in Economics' },];

const str1 = 'unnecessay texts Higher Education in Biology unnecessary texts';

const result = storedList.reduce((r,o) =>
  o.text.length > r.text.length && str1.includes(o.text) ? o : r
);

console.log(result);

本文链接:https://www.f2er.com/3156589.html

大家都在问