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

11dmarpk  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(145)

我想将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}|` });
              }
           }))
c3frrgcw

c3frrgcw1#

arr2.forEach(j => {
    if (!arr.some(e => e.obj === j.obj)) {
        arr.push({ obj: `${j.obj}|` });
    }
});
gzszwxb4

gzszwxb42#

const arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 1, name: 'one'}]
const ids = arr.map(o => o.id)
const filtered = arr.filter(({id}, index) => !ids.includes(id, index + 1))
console.log(filtered)
============
otherwise here is similiar you can try
const persons= [
      { id: 1, name: 'John',phone:'23' },
      { id: 2, name: 'Jane',phone:'23'},
      { id: 1, name: 'Johnny',phone:'56' },
      { id: 4, name: 'Alice',phone:'67' },
    ];
const unique = [...new Map(persons.map((m) => [m.id, m])).values()];

相关问题