循环数组对象拿取某两个值判断重复,若重复保存最后一条数据

需求:
数据为数组对象 判断数组中的对象中某两个key下的value是否一致,如果一致,删除掉,不保存当前行数据,只保存最后一行相同value的数据。
这样说明可能比较抽象,拿取例子说明

const data = [
{ 
   name:'小明' ,
   age:12,
   height:155,
},
  { 
   name:'小明' ,
   age:12,
   height:166,
},
  { 
   name:'小明' ,
   age:12,
   height:88,
},
 { 
   name:'小红' ,
   age:10,
   height:158,
},
]

以上这条数据我想通过一个方法,把相同的名字为‘小明’,年纪为‘12’的删去,只保存最后一条名字为‘小明’,年纪为‘12’的数据。

处理后的data应该为:
 data = [
  { 
   name:'小明' ,
   age:12,
   height:88,
},
 { 
   name:'小红' ,
   age:10,
   height:158,
},
]

思路:首先需要把原有的数组循环一遍,拿出数组中的对象,挨个对比,

const newArr = filter.reduce(function (prev: { name: any; age: any; }[], cur: { name: any; age: any; }) {
    let flag = false;
    let index = 0;
    if (prev) {
      index = prev.findIndex((item: { field: any; type: any; }) => {
        return item.name=== cur.name&& item.age=== cur.age;
      });
      flag = index !== -1;
    }
    if (prev.length === 0 || !flag) {
      prev.push(cur);
    } else if (flag) {
      prev.splice(index, 1, cur);
    }
    return prev;
  }, []);

猜你喜欢

转载自blog.csdn.net/weixin_40121676/article/details/118667884