Remove entry from array using another array

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

    If you are going to work with large arrays, this solution will perform very well. First convert array1 to a Map to make your lookups quick. Then go through array2 and subtract from your map to signify that the element should get removed. Then finally run through your map and add the keys that have values bigger than 0

    const array1 = [1, 1, 2, 3, 4];
    const array2 = [1, 2];
    
    const obj = array1.reduce((acc, cv) => {
        if (acc.has(cv)) acc.set(cv, acc.get(cv) + 1);
        else acc.set(cv, 1);
        return acc;
    }, new Map());
    
    array2.forEach(i => {
        if (obj.has(i)) obj.set(i, obj.get(i) - 1);
    });
    
    const res = [];
    obj.forEach((v, k) => { if (v) res.push(k); });
    console.log(res)

提交回复
热议问题