0

I am trying to filter my entites by tags array, that can look like this:

const tags = ["tag1", "tag2"];

Every entity has property tags, that can have existing tags, for example:

["tag1", "tag2", "tag3"];

Or:

["tag1", "tag2"];

I need to compare if the tags array and the tags array of entity has the same values. So far I have tried this code, but it returns an entity even if the two arrays dont have the same values (I'm guessing the includes() function is to blame).

tags.every((tag: any) => doc.tags.includes(tag));

Any ideas how can I check if the arrays have the same values?

Thank you in advance.

3
  • Do you mean same length and same items in the same place ? Commented Oct 27, 2020 at 13:25
  • But really, you need to decide which array is the one that has to have all the values (i.e., which gets the every and which gets the includes. Commented Oct 27, 2020 at 13:29
  • @known-as-bmf not necessary in the same place but same values and same length Commented Oct 27, 2020 at 13:34

1 Answer 1

2

You can also compare the length as well

tags.every((tag: any) => doc.tags.includes(tag)) && tags.length === doc.tags.length;
Sign up to request clarification or add additional context in comments.

3 Comments

I thought that there is some more elegant way to deal with this, but the length check works.
You should check the length first (for short circuiting) and this wont work in a scenario like this: ['a','b','a'] and ['a','b','c'].
Only applicable in case of duplicates, in that case first need to remove dups ones then made the comparison

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.