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

前端 未结 2 1903
没有蜡笔的小新
没有蜡笔的小新 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);

    0 讨论(0)
  • 2021-01-18 18:32

    Nina's answer is a good start but will miss any unique elements in array 2. This extends her answer to get the unique elements from each array and then combine them:

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

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