用set 去重
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); 打印结果: [ {id: 0, name: "小明"} {id: 1, name: "小张"} {id: 2, name: "小李"} {id: 3, name: "小孙"} ]
用reduce去重
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"}]
免费查看前端面试题真题
WX搜索 【MST题库】小程序查看