ES6数组去重

// 数组去重
{
   const arr = [1,2,3,4,1,23,5,2,3,5,6,7,8,undefined,null,null,undefined,true,false,true,'中文','','','hello','中文'];
   //  第一种
   const r = [...new Set(arr)];
   console.log(r); // [1, 2, 3, 4, 23, 5, 6, 7, 8, undefined, null, true, false, "中文", "", "hello"]

   
   // 第二种
   const R = arr.reduce((all,name) => all.includes(name) ? all :[...all,name],[]);
   console.log(R); // [1, 2, 3, 4, 23, 5, 6, 7, 8, undefined, null, true, false, "中文", "", "hello"]
   
   // 第三种
   const k = arr.filter((item, i) => i === arr.indexOf(item));
   console.log(k); // [1, 2, 3, 4, 23, 5, 6, 7, 8, undefined, null, true, false, "中文", "", "hello"]
}


// 统计每个元素在数组中出现的次数
{
   const arr = ['zhangsan', 'lisi', 'wangwu', 'zhangsan', 'lisi', 'wangwu','zhaosi','liuneng'];
   const r = arr.reduce((all, name) =>{
      if(name in all){
         all[name]++
      }else{
         all[name] = 1;
      }
      return all;
   },{});
   console.log(r); // {zhangsan: 2, lisi: 2, wangwu: 2, zhaosi: 1, liuneng: 1}
}

// 数组对象去重 { const arr = [ { name:'zhangsan', age:12 }, { name:'lisi', age:14 }, { name:'zhangsan', age:12 }, { name:'lisi', age:14 }, { name:'zhangsan', age:12 }, { name:'lisi', age:14 }, { name:'zhangsan', age:12 }, { name:'wangwu', age:16 }, { name:'wagnwu', age:16 }, { name:'lisi', age:14 }, ] // 根据 age 去重 // 方法一 const age = 'age'; const r = arr.reduce((all, next) => all.some((atom) => atom[age] == next[age]) ? all : [...all, next],[]); console.log(r); }

转载于: https://blog.csdn.net/weixin_30920597/article/details/96060520
上一篇:如何去除列表中重复的元素


下一篇:04SpringBoot配置文件