ES6 数组内对象去重
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ES6 数组内对象去重相关的知识,希望对你有一定的参考价值。
参考技术A 大神总结: https://www.cnblogs.com/caideyipi/p/7679681.html原文参考链接 https://blog.csdn.net/u010377383/article/details/79645839 (reduce)
https://blog.csdn.net/original_heart/article/details/79491768
扩展文章
es 数组去重,数组里面的对象去重
// 数组去重 { 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); }
以上是关于ES6 数组内对象去重的主要内容,如果未能解决你的问题,请参考以下文章