0

Essentially, I am trying to filter out specific indices that are not in criteria array. Data that I am getting from JSOn file looks like this:

let data = [
        {
            "category": ["business"],
            "title": "some title"
        },
        {
            "category": ["travel", "business"],
            "title": "some title"
        },
        {
            "category": ["sport"],
            "title": "some title"
        },
        {
            "category": ["business", "sport"],
            "title": "some title"
        }
    ]

The array that should filter category of each object from the data above:

var criteria = ["business", "travel"]

I've tried numerous options, the ones that I've listed below are only the ones that either return something or not bring any errors, however, both methods do not bring desired outcome.

const filtered = data.filter((item) => 
   // this returns only first "business" category while ignoring the rest
   criteria.find(element => item.category == element)
) 

const filtered = data.filter((item) => 
   // this simply returns all data entries, even the ones that are not in criteria array.
   criteria.filter(element => item.category == element)
) 
const filtered = spanishData.filter(function (item) {
    // returns all data entries as well
        return criteria.indexOf(item.category) === -1
    })

How can I filter the data > category array according to the criteria array?

Thank you

2
  • filter always returns an Array and an Array is always truthy. data.filter((item) => criteria.filter()) is effectively exactly the same as data.filter(() => true) which is the same as data.slice(). item.category == element doesn’t make sense: item.category is an Array. You can’t reliably compare it using ==; comparing a String and an Array with == coerces both operands to strings and "travel,business" is not "business,travel". Commented Dec 19, 2022 at 1:32
  • Duplicate of Filter array of objects where one object's array has at least one match with another array. Commented Dec 19, 2022 at 1:38

1 Answer 1

0

You can use Array#filter along with Array#some.

let data=[{category:["business"],title:"some title"},{category:["travel","business"],title:"some title"},{category:["sport"],title:"some title"},{category:["business","sport"],title:"some title"}],
criteria=["business","travel"];
let res = data.filter(x => x.category.some(c => criteria.includes(c)));
console.log(res);

Sign up to request clarification or add additional context in comments.

1 Comment

pretty sure this question has multiple duplicates, should have closed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.