Kevin L
Kevin L

Reputation: 23

JavaScript Array.includes - how to check multiple values with spread operator

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?

Upvotes: 1

Views: 1020

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

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); 

Upvotes: 4

Related Questions