I have two arrays, array A has a list of elements that may or may not contains an element from array B. I want to filter array A so that it only contains elements where it contains at least one element from array B.
const a = [
'cqAWS1x2',
'cqAM1c',
'cqA10a cqA10b',
'cqA10axZAF cqA10bxZAF']
const b = [
'cqAWS1x2',
'cqA10a',
'cqA10axZAF']
I want to filter a so it'll be
['cqAWS1x2',
'cqA10a cqA10b',
'cqA10axZAF cqA10bxZAF']
'cqAWS1x2'
because Array b contains that element, 'cqA10a cqA10b'
because b contains 'cqA10a' which is part of 'cqA10a cqA10b'
. Same for 'cqA10axZAF cqA10bxZAF'
, because b contains 'cqA10axZAF'.
This is what I have so far:
a.filter(avc => b.some(bvc => bvc.includes(avc)))
In the result, I get only ['cqAWS1x2'] but not 'cqA10a cqA10b'
and 'cqA10axZAF cqA10bxZAF'
.
Thanks for all the help!
CodePudding user response:
You just need to switch the avc
and bvc
in your includes()
call (avc
is the longer string, check if it includes the shorter bvc
).
const a = ['cqAWS1x2', 'cqAM1c', 'cqA10a cqA10b', 'cqA10axZAF cqA10bxZAF'];
const b = ['cqAWS1x2', 'cqA10a', 'cqA10axZAF'];
console.log(a.filter((avc) => b.some((bvc) => avc.includes(bvc))));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>