Home > Blockchain >  Find Efficient way of Filtering of two arrays (ArrayA & ArrayB) to make a third ArrayC
Find Efficient way of Filtering of two arrays (ArrayA & ArrayB) to make a third ArrayC

Time:07-05

Can anyone help me come up with a faster way of filtering the following ArrayC (see below what it should be equal to. ArrayA is self explanatory. ArrayB has inside of each element an object 'data' that has a property "target" as a string "\_teacher" that I can filter out based on a global variable "userType" to distinguish students vs teachers. "filter_klas_1371" ==> filter_{GroepType }_{GroepID} from Array A. This property changes. breaking the string and filtering has giving me a headache, so if there are faster more efficient ways to filter this please let me know.

let userType='teacher'

arrayA: [{
    "ID": 1,
    "GroepID": 1371,
    "GroepType": "klas"
  },
  {
    "ID": 2,
    "GroepID": 1372,
    "GroepType": "klas"
  },
  {
    "ID": 3,
    "GroepID": 1375,
    "GroepType": "graad"
  }
]

araayB: [{
"id": "bd5b12ba-b433-4610-801e-e0b78fa72ff8",
    data: {
      "target": "_teacher",
      "filter_klas_1371": "true"
    }
  },
  {
  "id": "gggfdgdba-gfgg-fff-ggg-7657657676",
    data:{
      "target": "_teacher_student",
      "filter_klas_1375": "true"
    }
  } {
  "id": "uuuykllk-b433-4610-801e-8888888776",
     data: {
      "target": "_student",
      "filter_klas_1372": "true"
    }
  } {
"id": "jkjkjkklk-jkhjk-66567-666-99977",
    data: {
      "target": "_teacher_student",
      "filter_klas_1372": "true"
    }
  },
  {
   "id": "zzzzzzz-b433-4610-801e-8888888776",
    data: {
      "target": "_teacher",
      "filter_klas_1372": "true"
    }
  },
]

//should get
arrayC:[{
"id": "bd5b12ba-b433-4610-801e-e0b78fa72ff8",
    data: {
      "target": "_teacher",
      "filter_klas_1371": "true"
    }
  },
  {
    data: {
    "id": "jkjkjkklk-jkhjk-66567-666-99977",
      "target": "_teacher_student",
      "filter_klas_1372": "true"
    }
  },
   {
     "id": "zzzzzzz-b433-4610-801e-8888888776",
    data: {
      "target": "_teacher",
      "filter_klas_1372": "true"
    }
  }
  ]

CodePudding user response:

If I understand correct you would like to filter arrayB based on the userType and the values in arrayA. I suggest making an array of all the possible filter_{groepType}_{groepId} with array map:

const filterKeys = arrayA.map(group => `filter_${group.GroepType}_${group.GroepID}`);

Then you can check if one of those values is set as a key in the keys of arrayB, using an intersection of array with a couple of filters. You can do this in more ways:

arrayC = arrayB.filter(item => {
  const intersect = Object.keys(item.data).filter(key => filterKeys.includes(key));
  return intersect.length > 0; // you can additionally add the filter for target here
})
  • Related