使用lodash模块迭代嵌套循环并返回匹配的值在Node.js中不起作用

我有两个名单。 第一个是值列表,其他是任何string可以包含这些值的string列表。 所以我正在遍历wordList,并在内部循环遍历值,当一个string包含值时,它应该返回值。

const _ = require('lodash'); const valueList = ['abb','bcd','ghi']; const wordList = ['ab','a','abc','abcde','bcef','aghif']; const selectedValue = _.filter(wordList, (word) => { return _.filter(valueList, (value) => { return _.includes(word,value); }); }); console.log(`Printing matched value ${selectedValue}`); // Output should be bcd as 'bcd' as wordList contains this value and also it is first match. 

你可能不需要lodash。 普通的JavaScript也可以做到这一点:

 const valueList = ['abb','bcd','ghi']; const wordList = ['ab','a','abc','abcde','bcef','aghif']; const selectedValue = valueList.find( val => wordList.some(word=>word.includes(val))); console.log(`Printing matched value ${selectedValue}`); // Output should be bcd as 'bcd' as wordList contains this value and also it is first match. 

使用lodash的工作代码。

 const _ = require('lodash'); const valueList = ['abb','bcd','ghi']; const wordList = ['ab','a','abc','abcde','bcef','aghif']; const selectedValue = _.filter(valueList, (value) => { return _.some(wordList, (word) => { return _.includes(word,value); }); }); console.log(`Printing matched value ${selectedValue}`);