Reputation: 139
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);
Upvotes: 0
Views: 73
Reputation: 350365
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);
Upvotes: 3