I have 2 arrays of the following format:
array1 = ['cat', 'man', 'new']
array2 = ['catch', 'jim', 'manners', 'renew', 'newcomer']
I am trying to find an array that contains items of array 2 if any of the strings in array 1 are contained in the string of array 2. In this case the output would be:
['catch', 'manners', 'renew', 'newcomer']
I know that I could to this with a forloop but am curious if there is a simpler 1 line solution for this?
Thanks!
CodePudding user response:
You can use RegExp.test()
and Array.join()
to create a regular expression using alternation:
const array1 = ['cat', 'man', 'new'];
const array2 = ['catch', 'jim', 'manners', 'renew', 'newcomer'];
const result = array2.filter(v => RegExp(array1.join('|')).test(v));
console.log(result);
Notes:
- You have to be careful when the strings include special characters, they will need to be escaped.
- From a performance perspective, it's better to build the
RegExp
once instead of creating it inside thefilter()
callback.
CodePudding user response:
With filter()
, some()
and includes()
this can be done in one line:
let array1 = ['cat', 'man', 'new'];
let array2 = ['catch', 'jim', 'manners', 'renew', 'newcomer'];
let ans = array2.filter(x => array1.some(a => x.includes(a)));
console.log(ans);
CodePudding user response:
array1 = ['cat', 'man', 'new']
array2 = ['catch', 'jim', 'manners', 'renew', 'newcomer']
const result = array2.filter(word => array1.some(phrase => word.includes(phrase)))
console.log(result)