记录三种类型数据去重的处理方法

1、单个数组内部
// 去重,对{}无效
var string= [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]
console.log('去重前的数据' + JSON.stringify(string)))
string = Array.from(new Set(string))
console.log('去重后的数据' + JSON.stringify(string)))
// [1, 'true', true, 15 ,false, undefined, null, NaN, 'NaN', 0, 'a',{},{}]
2、根据数组对象单个属性
var arr = [
  {
   from:'张三',
   to: '河南'
  },
  {
    from:'王二',
    to: '阿里'
  },
  {
    from:'王二',
    to: '杭州'
  },
  {
    from:'王二',
    to: '山东'
  },
]

function unique(arr1) {
  const res = new Map();
  return arr1.filter((a) => !res.has(a.from) && res.set(a.from, 1))
}
3、根据数组对象多个对象
let arr = [
      {
        maxDeptCode: "md3",
        maxDeptName: "泡泡",
        minDeptCode: "md301",
        minDeptName: "泡泡少儿",
        schoolId: 1,
        schoolName: "北京",
      },
      {
        maxDeptCode: "md2",
        maxDeptName: "中学",
        minDeptCode: "md201",
        minDeptName: "中学一对一",
        schoolId: 1,
        schoolName: "北京",
      }, {
        maxDeptCode: "md3",
        maxDeptName: "泡泡",
        minDeptCode: "md301",
        minDeptName: "泡泡少儿",
        schoolId: 1,
        schoolName: "北京",
      },
    ];

    function process(arr) {
      // 缓存用于记录
      const cache = [];
      for (const t of arr) {
        // 检查缓存中是否已经存在
        if (cache.find(c => c.maxDeptCode === t.maxDeptCode && c.minDeptCode === t.minDeptCode)) {
          // 已经存在说明以前记录过,现在这个就是多余的,直接忽略
          continue;
        }
        // 不存在就说明以前没遇到过,把它记录下来
        cache.push(t);
      }

      // 记录结果就是过滤后的结果
      return cache;
    }

    console.log(process(arr));
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/bugSource/p/14582566.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程