javascriptreactjsarraysfilter

Filter an array of objects based on multiple categories


The data looks like:

export const data = [
  {
    id: 1,
    company: "Photosnap",
    logo: "./images/photosnap.svg",
    new: true,
    featured: true,
    position: "Senior Frontend Developer",
    role: "Frontend",
    level: "Senior",
    postedAt: "1d ago",
    contract: "Full Time",
    location: "USA Only",
    languages: ["HTML", "CSS", "JavaScript"],
    tools: [],
  },
  {
    id: 2,
    company: "Manage",
    logo: "./images/manage.svg",
    new: true,
    featured: true,
    position: "Fullstack Developer",
    role: "Fullstack",
    level: "Midweight",
    postedAt: "1d ago",
    contract: "Part Time",
    location: "Remote",
    languages: ["Python, Javascript"],
    tools: ["React"],
  },
  // so on ...
]

I have to filter the data based on the following filter array:

const filter = ["HTML","CSS"]

I would have to display the item that consists of both "HTML" and "CSS", and in this case it would be just the first item in the data. What would the optimal way to achieve so?


Solution

  • you can check if every element in filter is included in languages

    const filteredData = data.filter(job =>
      filter.every(f => job.languages.includes(f))
    );