Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript .includes method on an array within an object

I want to filter through an array and retrieve items if their filters match. However it does not work.

const wanted=["apple"]
const items = [
  {
    "name": "Iphone"
    "filters": ["phone","apple"]
  },
  {
    "name": "samsung12"
    "filters": ["samsung12","samsung"]
  },
]

let desiredList = items.filter((val) => wanted.includes(val.filters));

Any ideas on how i could get this to work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You would need to use some to check if any of the filters contains a value in wanted:

const wanted = ["apple"]
const items = [{
  "name": "Iphone",
  "filters": ["phone", "apple"]
}, {
  "name": "samsung12",
  "filters": ["samsung12", "samsung"]
}];

let desiredList = items.filter((item) => item.filters.some((f) => wanted.includes(f)));

console.log(desiredList);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading