首页 > 解决方案 > 在短语数组和字符串变量之间创建一个完全匹配的数组

问题描述

我有一系列短语,例如:

let structures = ['to earth' ,'to protect you', 'i do', 'i love', 'i was sent', 'i want'];

我有一个字符串变量,例如:

let speechResult = 'i was sent to mars and earth i wanted i love'

我想根据数组中短语和字符串变量的完全匹配创建一个新数组。

上述示例的预期结果将是:

let newArr = [ 'i was sent', 'i love'];

注意:代码的性能很重要!

更新:我这样做了,但这有两个问题:

-第一:我没有得到预期结果的顺序。

-第二:没有完全匹配,所以我根本没有得到预期的结果。

    let structures = ['to earth' ,'to protect you', 'i do', 'i love', 'i was sent', 'i want'];
    
    let speechResult = 'i was sent to mars and earth i wanted i love'
    let newArr = [];
    
    for(let i = 0; i < structures.length; i++ ){
    
        if(speechResult.includes(structures[i])){
        
           newArr.push(structures[i]);
        
        }
    }
    
    
    console.log(newArr)

标签: javascript

解决方案


这基本上很容易通过过滤来解决:

let structures = ['to earth' ,'to protect you', 'i do', 'i love', 'i was sent', 'i want'];
let speechResult = 'i was sent to mars and earth i wanted i love'

const newArr = structures.filter((structure) => speechResult.includes(structure));

console.log(newArr);

但正如您所看到的,“我想要”也包含(因为 SpeechResult 包含“我想要”)。因此,我们必须使用正则表达式来排除此类部分命中:

let structures = ['to earth' ,'to protect you', 'i do', 'i love', 'i was sent', 'i want'];
let speechResult = 'i was sent to mars and earth i wanted i love'

const newArr = structures.filter((structure) => {
  const rg = new RegExp(`(${structure})(?![a-z]+)`,'gi');
  return speechResult.match(rg);
});

console.log(newArr);

这会给我们正确的结果(我会说非常有效)。


推荐阅读