在实际的项目当中不可避免的会遇到数组里面元素重复情况,下面将介绍几种ES6数组去重的方法:
1、使用Set去重
const arr = ['张三','张三','三张三'] let set = new Set(arr); // set 自带去重 // Set { '张三', '三张三' } console.log(set); console.error(Array.from(set)); // [ '张三', '三张三' ]
2、使用reduce去重
let person = [ {id: 0, name: "小明"}, {id: 1, name: "小张"}, {id: 2, name: "小李"}, {id: 3, name: "小孙"}, {id: 1, name: "小周"}, {id: 2, name: "小陈"}, ]; let obj = {}; let peon = person.reduce((cur,next) => { obj[next.id] ? "" : obj[next.id] = true && cur.push(next); return cur; },[]) //设置cur默认类型为数组,并且初始值为空的数组 console.log(peon); // (4) [{…}, {…}, {…}, {…}]0: {id: 0, name: "小明"}1: {id: 1, name: "小张"}2: {id: 2, name: "小李"}3: {id: 3, name: "小孙"}length: 4__proto__: Array(0)
3、使用reduceRight去重,颠倒数组顺序
let hash = {}; let config = [{ name: 2, state: true, output: 'Y', }, { name: 3, state: true, output: 'A', }, { name: 5, state: true, output: 'S', }, { name: 7, state: true, output: 'B', }]; config = [...config, { name: 3, state: false, output: 'A', }] const newArr = config.reduceRight((item, next) => { hash[next.name] ? '' : hash[next.name] = true && item.push(next); return item }, []); console.log(JSON.stringify(newArr)); // [{"name":3,"state":false,"output":"A"},{"name":7,"state":true,"output":"B"},{"name":5,"state":true,"output":"S"},{"name":2,"state":true,"output":"Y"}]