Array filter is not returning correct value

Viewed 104

I am using react-admin framework. I am creating an intersection of two arrays that should return one or multiple elements if the conditions return true. However the last condition gets skipped for some reason.

const filterWithTags = response.docs.filter((doc: any) => doc.hasOwnProperty("tags") && doc.tags.length > 0 && (tags as any).filter((tag: any) => doc.tags.includes(tag)));

This code returns only elements that match the first two conditions (hasOwnProperty and length> 0). I need it to continue to the includes condition as well. Any ideas what Im doing wrong?

Thank you in advance

2 Answers

You need to check whether tags contains some data:

const filterWithTags = response.docs.filter((doc: any) => doc.hasOwnProperty("tags") 
    && doc.tags.length > 0 
    && (tags as any).some((tag: any) => doc.tags.includes(tag)));

If doc has property tags and doc.tags has items, then we can check whether it contains some tags by doc.tags.

This part of your condition is always treated as true -(tags as any) .filter ((tag: any) => doc.tags.includes (tag)) Even if there are not any values ​​that meet conditions filter always returns an empty array. Any type of array treated as true in JS.

Related