Search code examples
javascriptarraysobjectarray-filterarrayofarrays

searching an array of objects on the basis of value present inside an value of an object in form of array


I have an an object with two fields filter1 and filter2 having values in form of array

let filter = {filter1:["mine","your"]: filter2:["C","D"]} //values not fixed

the data is in form of array of objects

let data = [
{ id:1, filter1:["mine"], filter2:["E","C"]},
{ id:2, filter1:["mine"], filter2:["E","C","F"]},
{ id:3, filter1:["your"], filter2:["C"]},
{ id:3, filter1:["your"], filter2:["D","C"]},
{ id:5, filter1:["other"], filter2:["F"]},
...
]

I have to filter out those objects which have any one of the fields present in specific key for eg if filter is {filter1:["mine"]: filter2:["F","D"]} it will first search for any element of filter1 in filter1 of data object and after that search for any element of filter2 which is present in the filter2 of data object and return the object if any one them is found

few example

result for {filter1:["mine"]: filter2:["F","D"]}

result = [
{ id:1, filter1:["mine"], filter2:["E","C"]}, //since filter1 "mine"
{ id:2, filter1:["mine"], filter2:["E","C","F"]}, //since filter1 "mine"
{ id:3, filter1:["your"], filter2:["D","C"]}, //since from "F" and "D" from filter2 "D" is present
{ id:5, filter1:["other"], filter2:["F"]}, //since "F" from filter2 is present
]

result for {filter1:["your"]: filter2:["F","G"]}

result = [
{ id:2, filter1:["mine"], filter2:["E","C","F"]}, //since "F" from filter2 is present
{ id:3, filter1:["your"], filter2:["D","C"]}, //since filter1 is "your"
{ id:5, filter1:["other"], filter2:["F"]}, //since "F" from filter2 is present
]

result for {filter1:[]: filter2:["D"]}

result = [
{ id:3, filter1:["your"], filter2:["D","C"]}, //since filter2 has "D"
]

Solution

  • You can use a combination of .filter(), .some() and .includes():

    const data = [
      { id:1, filter1:["mine"], filter2:["E","C"]},
      { id:2, filter1:["mine"], filter2:["E","C","F"]},
      { id:3, filter1:["your"], filter2:["C"]},
      { id:3, filter1:["your"], filter2:["D","C"]},
      { id:5, filter1:["other"], filter2:["F"]}
    ];
    
    const search = ({ filter1, filter2 }) => 
      data.filter(item => 
        item.filter1.some(fItem => filter1.includes(fItem)) ||
        item.filter2.some(fItem => filter2.includes(fItem))
    );
    
    const result = search({ filter1:["mine"], filter2:["F","D"] });
    console.log(result);