如何在JavaScript中删除对象数组中的重复对象

问题描述 投票:0回答:2

我想删除重复的对象。我该怎么办?

const array1 = [{ currencyName : "USD", code: "121" }, 
                { currencyName : "INR", code: "123" }];

const array2 = [{ currencyName : "USD", code: "121" }];

Result = [{ currencyName : "INR", code: "121" }]
javascript arrays
2个回答
0
投票

尝试使用filtersome方法:

const array1 =[ 
    { currencyName : "USD", code: "121" }, 
    { currencyName : "INR", code: "123" }
]

const array2=[ { currencyName : "USD", code: "121" }];

const result = array1.filter(f=> 
    !array2.some(s=> f.code === s.code && f.currencyName === s.currencyName)
);

console.log(result)

0
投票

const array1 = [{
  currencyName: "USD",
  code: "121"
}, {
  currencyName: "INR",
  code: "123"
}, ]

const array2 = [{
  currencyName: "USD",
  code: "121"
}, {
  currencyName: "FRA",
  code: "122"
}]

let array1Uniques = array1.filter(a => !array2.some(b => b.code === a.code));
let array2Uniques = array2.filter(a => !array1.some(b => b.code === a.code));
let result = [...array1Uniques,  ...array2Uniques];
console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.