I am working on a Vuejs project where I have an array of posts. I have a menu where I can select one or more categories which updates the array of posts to only display the posts with the categories selected. Due to the project code having to be protected, I created a dummy example.
const arr = [
{
id: 1,
categories: ["animals"]
},
{
id: 2,
categories: ["cities"]
},
{
id: 3,
categories: ["house"]
},
{
id: 4,
categories: ["house", "cities"]
},
{
id: 5,
categories: ["new"]
}
];
const selectedItems = ["house", "new"];
const filteredArr = arr.filter((a) => a.categories.includes(...selectedItems));
console.log("result", filteredArr);
// "result", [ { id:3, categories: ["house"] }, { id: 4, categories: ["house", "cities"]} ]
The issue that I am currently running into is that when I spread the variable selectedItems into the .includes() array method, it only targets the first item in that array which is "house". As a result I only return the posts with the id 3 & 4 while not returning id 5 which has the "new" category tied to it.
How would I be able to return all the posts based on the categories that I have selected? Is .includes() even the correct array method?