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

Filter array of objects by property with array of strings with an array of strings

So I have data that looks like this:

    const data = [
      { foo: ["0001|main|0002", "0001|main|0014", "0001|main|0016"] },
      { foo: ["0001|main|0014", "0001|main|0018", "0001|main|0019"] },
      { foo: []},
      { foo: ["0001|main|0001", "0001|main|0012", "0001|main|0022"] },
    ];

And I need to filter it with an array of strings that looks like this:

let selections = ["0014", "0016"];

I need to match the items with the same last for numbers only in the data,
I currently have this which sort of works:

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

data.filter((item) => {
 if(!item.foo.length) return false;
 return selections.every((id) => item.foo.split('|')[2] === id)
});

The issue I’m having that when selecting two IDs like above it returns nothing.
I was expecting the return value to be this:

[
 {foo: ["0001|main|0002", "0001|main|0014", "0001|main|0016"]},
 {foo: ["0001|main|0014", "0001|main|0018", "0001|main|0019"]},
]

I works fine when selection has only one string in it. I think its searching for items that match both strings in the selection.

Any help would be appreciated!

>Solution :

Since you want

["0001|main|0014", "0001|main|0018", "0001|main|0019"]

to be included, it sounds like you need at least one of the selections to match, rather than every selection to have a match. So, use .some instead of .every.

const data = [
  { foo: ["0001|main|0002", "0001|main|0014", "0001|main|0016"] },
  { foo: ["0001|main|0014", "0001|main|0018", "0001|main|0019"] },
  { foo: []},
  { foo: ["0001|main|0001", "0001|main|0012", "0001|main|0022"] },
];
const selections = ["0014", "0016"];

const result = data.filter(
  ({ foo }) => selections.some(
    sel => foo.some(
      str => str.endsWith(sel)
    )
  )
);
console.log(result);      
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