Remove entry from array using another array

前端 未结 7 1952
迷失自我
迷失自我 2021-01-25 09:12

Not sure how do to this, so any help is greatly appreciated

Say I have :

const array1 = [1, 1, 2, 3, 4];
const array2 = [1, 2];

Desired

7条回答
  •  时光说笑
    2021-01-25 09:35

    IMO using array2 as object instead of array will be most performant way.

    Here on first find of key we change the value in object so we do not filter that value again as desired in output.

    const array1 = [1, 1, 2, 3, 4];
    const array2 = Object.create(null,{
      1:{writable: true,value:false}, 
      2:{writable: true,value:false}
    })
    
    
    let op = array1.filter(e=> {
      if(array2[e] === false){
        array2[e] = true
        return false
      }
      return true
    })
    
    console.log(op)

    On Side note:- With object.create we are creating a object without a prototype so it do not search for values in complete prototype chain.

提交回复
热议问题