2017-09-22 60 views
1

我有兩個列表。第一個是值列表,其他是任何字符串可以包含這些值的字符串列表。所以我正在迭代wordList,並在內部循環遍歷值時,如果字符串包含值,它應該返回值。使用lodash模塊對Node.js進行迭代嵌套循環並返回匹配值不起作用

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. 

回答

1

你可能不需要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.

0

工作代碼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}`);

+0

您的片段不起作用 –

+0

返回BCD,GHI – jyoti