Skip to content Skip to sidebar Skip to footer

Javascript - Filter Object Based On Multiple Values

I need to filter some data based on multiple values. Language, title and slug [ { de: '4567uy55', en: '654321', lang: [ { id: '654321', language:

Solution 1:

Instead of mixing for loops and functional chaining you could just go with one of them:

 multiFilter = (arr, filters) => 
   arr.map(flatten).filter(el => // filter out elements from arr
     Object.entries(filters).every(([fKey, fValues]) => // ensure that every key is included in the object
       Object.entries(el).some(([oKey, oValue]) => 
          oKey.split("/").includes(fKey) && fValues.includes(oValue)// make sure that at least one of the values equals the elements value
       )
     )
  );

Solution 2:

arr.filter(course => {
    // Returns an array of booleans corresponding to whether or not each filter condition is satisfied
    return Object.keys(filters).map(key => {
        return filters[key].map(filter => {
            // Special case here because lang is an array
            if (key == 'language' && course.lang != undefined) {
                return course.lang.some(lang => lang[key].includes(filter))
            }

            if (course[key] == undefined) {
                return false
            }

            return course[key].includes(filter)
        }).every(result => result == true)
    }).every(result => result == true)
})

Post a Comment for "Javascript - Filter Object Based On Multiple Values"