Deduplication of JS object arrays, forming a new array of objects with different fields in the two object arrays and returning

need

idThere are the following two object arrays, it is necessary to filter out the objects in arr1 that are different from arr2 , form a new array and return

Raw data

const arr1 = [
	{
    
     id: 1, name: '泡泡哥', age: 18 },
	{
    
     id: 2, name: '胡老板', age: 16 },
    {
    
     id: 3, name: '瓜瓜龙', age: 22 },
    {
    
     id: 4, name: '小肥兔', age: 20 },
]

const arr2 = [
	{
    
     id: 2, name: '鸡鸡爆', age: 32 },
	{
    
     id: 4, name: '琦老板', age: 99 },
    {
    
     id: 5, name: '哈撒K', age: 99 },
]

expected data

[
    {
    
     id: 1, name: '泡泡哥', age: 18 },
    {
    
     id: 3, name: '瓜瓜龙', age: 22 },
]

Implementation

method one

const newArr= arr1.filter((item) => arr2.every((val) => val.id !== item.id))
console.log(newArr)

Method Two

const newArr = arr1.filter((item) => !arr2.some((val) => val.id === item.id))
console.log(newArr)

method three

const getId = arr2.map(item => item.id) 
const newArr = arr1.filter(item => !getId.includes(item.id))
console.log(newArr)

Guess you like

Origin blog.csdn.net/weixin_43417844/article/details/129945292