How to get the difference of two string arrays?

前端 未结 3 1076
猫巷女王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条回答
  • 2021-01-15 06:27

    You could remove elements from allowed based on the input array:

     const allowed = ['T','E','A','P','A','P','E','R'];
     const input = ['T','A','P'];
    
     for(const char of input) {
       const pos = allowed.indexOf(char);
       if(pos === -1) {
         // char doesnt exist?
       } else {
         allowed.splice(pos, 1);
       }
     }
    

    Then allowed will be your expected result at the end.

    0 讨论(0)
  • 2021-01-15 06:29

    I think filter is not correct apparoch here. Because there are some elements repeadted. Use a simple for-loop. And remove the elements when you add it to result.

    const array1 = ['T','E','A','P','A','P','E','R'];
    const array2 = ['T','A','P'];
    const copy = [...array2];
    
    let res = [];
    for(let i = 0;i<array1.length;i++){
      let index = copy.indexOf(array1[i]);
      if(index === -1){
        res.push(array1[i]);
      }
      else copy.splice(index,1);
      
    
    }
    console.log(res)

    0 讨论(0)
  • 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);

    0 讨论(0)
提交回复
热议问题