简体   繁体   中英

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?

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 include d

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM