Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare two arrays and remove partially matched strings

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading