Remove entry from array using another array

前端 未结 7 1974
迷失自我
迷失自我 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:21

    This will run reasonably well. I think its linear time instead of N*N

    function diffOnlyOncePerElementInstance(a1, a2) {
      const max = Math.max(a1.length, a2.length);
      const map = {};
    
      for (let i = 0; i < max; i++) {
        const valueA = a1[i];
        const valueB = a2[i];
        if (i < a1.length) {
          if (!Number.isInteger(map[valueA])) {
            map[valueA] = 0;
          }
          map[valueA]++;
        }
        if (i < a2.length) {
          if (!Number.isInteger(map[valueB])) {
            map[valueB] = 0;
          }
          map[valueB]--
        }
      }
    
      return Object.keys(map)
        .map(key => new Array(Math.abs(map[key])).fill(key)) // regenerate remaining count
        .reduce((a,b) => a.concat(b), []); // flatten
    }
    

提交回复
热议问题