How to get the difference of two string arrays?

前端 未结 3 1075
猫巷女王i
猫巷女王i 2021-01-15 05:51

I want to get the exact difference between two string arrays.

const array1 = [\'T\',\'E\',\'A\',\'P\',\'A\',\'P\',\'E\',\'R\'];
const array2 = [\'T\',\'A\',\         


        
3条回答
  •  -上瘾入骨i
    2021-01-15 06:40

    You could take a closure over the index for the second array and increment the index and remove this item from the result set.

    var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'],
        array2 = ['T', 'A', 'P'],
        result = array1.filter((i => v => array2[i] !== v || !++i)(0));
    
    console.log(result);

    A different approach without a predefined order of array2.

    var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'],
        array2 = ['T', 'A', 'P'],
        set2 = new Set(array2)
        result = array1.filter(v => !set2.delete(v));
    
    console.log(result);

提交回复
热议问题