i’m having trouble filtering an array based on partially matched content from another.
var arrayComplete = [
'blue.house',
'blue.bird',
'blue.ocean',
'red.chair',
'red.curtain',
'black.screen',
'green.grass',
'green.parrot'
];
var arrayToRemove = [blue, red];
I need to end up with an array that had elements removed based on partial string matchs:
For example, in this case, based on having the colours "blue" and "red" all elements that had "blue" and "red" on their string were removed
['black.screen','green.grass','green.parrot'];
Any tips?
I’m trying
let newArray = arrayComplete.filter((e) => arrayToRemove.includes(e))
But returns empty array. I assume because it’s not matching partial strings.
>Solution :
Go over the elements, split them at the dot and check if any of the parts are contained in the excluded elements:
var arrayComplete = [
'blue.house',
'blue.bird',
'blue.ocean',
'red.chair',
'red.curtain',
'black.screen',
'green.grass',
'green.parrot'
];
var arrayToRemove = ['blue', 'red'];
const f = (arr, els) => arr.filter(it => it.split('.').every(v => !els.includes(v)))
console.log(f(arrayComplete, arrayToRemove))