1

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?

1 Answer 1

4

includes is fine, but you can't use it on its own - try linking it with some to make sure at least one of the selectedItems is included

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) => selectedItems.some(item => a.categories.includes(item)));

console.log("result", filteredArr); 

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.