Cuatro métodos para eliminar duplicados de objetos de matriz js según el ID

Por ejemplo: desea eliminar elementos duplicados con ID 1

arr = [
  { id: 1, name: '张三', age: 20 },
  { id: 1, name: '张三', age: 20 },
  { id: 2, name: '李四', age: 20 },
  { id: 3, name: '马五', age: 20 }
];

método uno

Utilice forEach y luego utilice el método some para determinar si la matriz contiene el ID del objeto actual. Si no es así, agréguelo.

some() {
  let some: any = [];
  this.arr.forEach(el => {
    if (!some.some(e => e.id == el.id)) {
      some.push(el);
    }
  });
  console.log(some);
}

Método dos

Utilice forEach y luego utilice el método find para determinar si la matriz contiene el ID del objeto actual. Si no es así, agréguelo.

find() {
  let find: any = [];
  this.arr.forEach(el => {
    if (!find.find(e => e.id == el.id)) {
      find.push(el);
    }
  });
  console.log(find);
}

Método tres

A través del método de reducción y el obj definido, determine si existe obj [next.id], si existe, configúrelo en "". Si no existe, presione

reduce() {
  let obj = {};
  let reduce = [];
  reduce = this.arr.reduce(function (item, next) {
    //item为没有重复id的数组,next为当前对象
    obj[next.id] ? '' : (obj[next.id] = true && item.push(next));
    return item;
  }, []);
  console.log(reduce);
}

Método cuatro

Recorra el bucle for y luego use el método some para determinar si la matriz contiene la identificación del objeto actual. Si no es así, agréguela.

forAway() {
  let forData = [];
  for (let i = 0; i < this.arr.length; i++) {
    if (!forData.some(e => e.id == this.arr[i].id)) forData.push(this.arr[i]);
  }
  console.log(forData);
}

おすすめ

転載: blog.csdn.net/m0_69429961/article/details/131166792