如何使用 find 方法从该对象数组中删除重复元素?

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

我想将 arr2 的元素推入 arr1 但它不应该重复这些元素

let arr = [{obj: "ABC"},{obj: "XYZ"},{obj: "LMN"}]
const arr2 = [{obj: "ABC"},{obj: "MNO"}]
 
arr2.forEach(j => {
           arr.find((e =>{
              if(j.obj !== e.obj){
                arr.push({ obj: `${j.obj}|` });
              }
           }))
javascript node.js reactjs json ecmascript-6
1个回答
0
投票

find 方法实际上并不是解决这个问题的最佳方法。 要将 arr2 中的元素推送到 arr 而不重复,可以在推送之前检查该对象是否已存在于 arr 中。这是更新版本:

let arr = [{ obj: "ABC" }, { obj: "XYZ" }, { obj: "LMN" }];
const arr2 = [{ obj: "ABC" }, { obj: "MNO" }];

arr2.forEach((j) => {
  // Check if the object is not already in arr
  if (!arr.some((e) => e.obj === j.obj)) {
    arr.push({ obj: j.obj });
  }
});

console.log(arr);

© www.soinside.com 2019 - 2024. All rights reserved.