filter array of objects by another array of objects

后端 未结 4 1957
日久生厌
日久生厌 2020-12-08 23:22

I want to filter array of objects by another array of objects.

I have 2 array of objects like this:

const array = [
    { id: 1, name: \'a1\', sub: {         


        
4条回答
  •  萌比男神i
    2020-12-08 23:56

    Ok, let's solve this step by step.

    To simplify the process let's suppose that two elements can be considered equals if they both have the same id.

    The first approach that I would use is to iterate the first array and, for each element, iterate the second one to check the conditions that you've defined above.

    const A = [ /* ... */]
    const B = [ /* ... */]
    
    A.filter(el => {
      let existsInB = !!B.find(e => {
        return e.id === el.id
      }
    
      return existsInB && !!B.sub
    })
    

    If we are sure that the elements in A and in B are really the same when they have the same ID, we could skip all the A elements without the sub property to perform it up a little bit

    A.filter(el => {
      if (!el.sub) return false
    
      let existsInB = !!B.find(e => {
        return e.id === el.id
      }
    
      return existsInB
    })
    

    Now, if our arrays are bigger than that, it means that we are wasting a lot of time looking for the element into B. Usually, in these cases, I transform the array where I look for into a map, like this

    var BMap = {}
    B.forEach(el => {
      BMap[el.id] = el
    })
    
    A.filter(el => {
      if (!el.sub) return false
    
      return !!BMap[el.id]
    })
    

    In this way you "waste" a little bit of time to create your map at the beginning, but then you can find your elements quicker.

    From here there could be even more optimizations but I think this is enought for this question

提交回复
热议问题