数组根据对象id去重的几种方法

2023-11-07

  arr = [
    { id: 1, name: '张一', age: 20 },
    { id: 1, name: '张一', age: 20 },
    { id: 2, name: '张二', age: 20 },
    { id: 3, name: '张三', age: 20 },
  ];

方法一

通过forEach再通过some方法判断数组是否包含当前对象id,不包含则添加

  some() {
    let some: any = [];
    this.arr.forEach(el => {
      if (!some.some(e => e.id == el.id)) {
        some.push(el);
      }
    });
    console.log('%c [ some去重结果 ]-43', 'font-size:13px; background:pink; color:#bf2c9f;', some);
  }

方法二

通过forEach再通过find方法判断数组是否包含当前对象id,不包含则添加

  find() {
    let find: any = [];

    this.arr.forEach(el => {
      if (!find.find(e => e.id == el.id)) {
        find.push(el);
      }
    });
    console.log('%c [ find去重 ]-51', 'font-size:13px; background:pink; color:#bf2c9f;', find);
  }

方法三

通过reduce方法,通过定义的obj,判断obj[next.id] 是否存在,存在设置为“”,不存在则push

  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);
  }

方法四

通过for循环遍历,再通过some方法判断数组是否包含当前对象id,不包含则添加

  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('%c [ forData ]-74', 'font-size:13px; background:pink; color:#bf2c9f;', forData);
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

数组根据对象id去重的几种方法 的相关文章