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

Alright
  • 1
  • 1
  • [`filter`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) always returns an Array and an Array is always [truthy](//developer.mozilla.org/en/docs/Glossary/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"`. – Sebastian Simon Dec 19 '22 at 01:32
  • [Duplicate](//google.com/search?q=site:stackoverflow.com+js+filter+objects+where+array+property+contains+at+least+one+item+from+another+array) of [Filter array of objects where one object's array has at least one match with another array](/q/65550533/4642212). – Sebastian Simon Dec 19 '22 at 01:38

1 Answers1

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);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80