Search code examples
javascripttypescriptunderscore.jslodash

Filter multiple array object with multiple property


Im trying to create a filter function where it can return a result of data that matches the value that i am looking for , from the given set of string keys

example of array:

let data = [
 { id:1 , data:{ name:"sample1",address:{ cat:"business" } } },
 { id:2 , data:{ name:"sample2",address:{ cat:"office"  }  } },
 { id:3 , data:{ name:"sample3",address:{ cat:"office"  } } },
 { id:4 , data:{ name:"sample4",address:{ cat:"office"  }  } }
 { id:5 , data:{ name:"sample5",address:{ cat:"home"  } } }
 { id:6 , data:{ name:"sample6",address:{ cat:"home"  }  } }
]



function filter( collection , value ,key ){
  //code 
}


let result = filter( data , "business" , [ "data","address","cat" ] )

console.log(result)

expected result is

{ id:1 , data:{ name:"sample1",address:{ cat:"business" } } },


Solution

  • You can use filter to search for the data. Use reduce to construct the keys.

    Note: filter returns an array of matched elements. If you prefer the first match only, you can use find

    const data = [
      { id: 1, data: { name: "sample1", address:{ cat: "business" } } },
      { id: 2, data: { name: "sample2", address:{ cat: "office" } } },
      { id: 3, data: { name: "sample3", address:{ cat: "office" } } },
      { id: 4, data: { name: "sample4", address:{ cat: "office" } } },
      { id: 5, data: { name: "sample5", address:{ cat: "home" } } },
      { id: 6, data: { name: "sample6", address:{ cat: "home" } } }
    ]
    
    const filter = (collection, keys, value) => 
      collection.filter(o => keys.reduce((c, v) => c[v] || {}, o) === value)
    const result = filter(data, ["data", "address", "cat"], "business")
    
    console.log(result)