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:
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);