简体   繁体   中英

filter array of objects based on list of values

I have an array as following

array = [
{
  name: 'A'
  instructors: [
   {
     name:'InsA'
   }
  ]
  businessUnit: {name:'myBusiness'}
},
{
  name: 'B'
  instructors: [
   {
     name:'InsB'
   }
  ]
  businessUnit: {name:'myBusinessB'}
}

]

I want to filter this array with the values i have which are also in an array as following

nameArr = [A,C,D]
instructorArr = [InsA,InsC,InsZ]
businessName = [myBusinessB,myBusinessX,myBusinessD]

If can filter this array if i have to check with just one value as following

const filtered = _.filter(groupActivityList, (obj) => {
      return (
        obj.name === (groupClassFilter !== defaultFilter ? groupClassFilter : obj.name) &&
        obj.instructors.length > 0 &&
        obj.instructors[0]?.name ===
          (groupInstructorFilter !== defaultFilter
            ? groupInstructorFilter
            : obj.instructors.length > 0 && obj.instructors[0]?.name) &&
        obj.businessUnit.name ===
          (groupFacilityFilter !== defaultFilter ? groupFacilityFilter : obj.businessUnit.name)
      );
    });

How do i filter when i have a set of values to filter with Ex: nameArr = [A,C,D]

An example for filtering the array using Array.prototype.some and Array.prototype.includes :

 const array = [{ name: 'A', instructors: [{ name: 'InsA' }], businessUnit: { name: 'myBusinessA' } }, { name: 'B', instructors: [{ name: 'InsB' }], businessUnit: { name: 'myBusinessB' } }, { name: 'Z', instructors: [{ name: 'InsZZ' }], businessUnit: { name: 'myBusinessZZ' } } ]; const nameArr = ['A', 'C', 'D'] const instructorArr = ['InsA', 'InsC', 'InsZ'] const businessName = ['myBusinessB', 'myBusinessX', 'myBusinessD', 'myBusinessA'] const filtered = array.filter(el => nameArr.includes(el.name) && el.instructors.some(ins => instructorArr.some(iA => ins.name === iA)) && businessName.includes(el.businessUnit.name) ); console.log(filtered);

You can use the Array#some property, if I understand the question correctly.

Instead of checking obj.name === filterObj.name , you can check with fiterObj.names.some(name => name === obj.name) which will return true if any of the elements inside the namesArr matches the object's name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM