Compare two Arrays with Objects and create new array with unmatched objects

前端 未结 2 1902
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 17:54

I have the following two Javascript arrays:

const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];
<
2条回答
  •  天涯浪人
    2021-01-18 18:16

    You could reverse the comparison (equal instead of unqual) and return the negated result of some.

    const
        array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
        array2 = [{ id: 1 }, { id: 3 }],
        array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id));
        //                               ^                                ^^^
    
    console.log(array3);

提交回复
热议问题