最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Compare two Arrays with Objects and create new array with unmatched objects - Stack Overflow

programmeradmin1浏览0评论

I have the following two Javascript arrays:

const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];

I now want a new array array3 that contains only the objects that aren't already in array2, so:

const array3 = [{ id: 2}, { id: 4 }];

I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.

const array3 = array1.filter(entry1 => {
  return array2.some(entry2 => entry1.id !== entry2.id);
});

Any idea? ES6 welcome

I have the following two Javascript arrays:

const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];

I now want a new array array3 that contains only the objects that aren't already in array2, so:

const array3 = [{ id: 2}, { id: 4 }];

I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.

const array3 = array1.filter(entry1 => {
  return array2.some(entry2 => entry1.id !== entry2.id);
});

Any idea? ES6 welcome

Share Improve this question asked Dec 4, 2017 at 22:08 mxmtskmxmtsk 4,6856 gold badges26 silver badges48 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 20

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);

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)

  1. 暂无评论