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.

AdamSulc
  • 330
  • 2
  • 4
  • 19

1 Answers1

2

You can also compare the length as well

tags.every((tag: any) => doc.tags.includes(tag)) && tags.length === doc.tags.length;
Aadil Mehraj
  • 2,586
  • 1
  • 7
  • 17
  • 1
    I thought that there is some more elegant way to deal with this, but the length check works. – AdamSulc Oct 27 '20 at 13:37
  • 1
    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']`. – known-as-bmf Oct 27 '20 at 13:43
  • Only applicable in case of duplicates, in that case first need to remove dups ones then made the comparison – Aadil Mehraj Oct 27 '20 at 14:18