0

I have an array of objects (array1). I want to filter every element, that includes ALL of the tags ([1, 2, 3). So the result should be id 1. But i cannot make it work. The results i get are id 1, 2 ,4 and i do not understand why exactly it acts like this.

let array1 = [
  { id: 1, tags: [1, 2, 3] },
  { id: 2, tags: [2, 3] },
  { id: 3, tags: [0, 3] },
  { id: 4, tags: [1, 3] }
];

let tags = [1, 2, 3];

let includesAll = array1.filter((a1) =>
  a1.tags.every((tag) => tags.includes(tag))
);

console.log(includesAll);

1 Answer 1

3

You should do the opposite. Instead of verifying that every value in a1.tags is also in tags, you'll want to verify that every value in tags is also in a1.tags:

let includesAll = array1.filter((a1) =>
  tags.every((tag) => a1.tags.includes(tag))
);

let array1 = [
  { id: 1, tags: [1, 2, 3] },
  { id: 2, tags: [2, 3] },
  { id: 3, tags: [0, 3] },
  { id: 4, tags: [1, 3] }
];

let tags = [1, 2, 3];

let includesAll = array1.filter((a1) =>
  tags.every((tag) => a1.tags.includes(tag))
);

console.log(includesAll);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.