ES6 数组内对象去重

image.png

去重Set

const arr = ['张三','张三','三张三']
let set = new Set(arr); // set 自带去重
// Set { '张三', '三张三' }
console.log(set);
console.error(Array.from(set)); // [ '张三', '三张三' ]
可直接在控制台粘贴打印 f12
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)

去重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"}]

大神总结: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

扩展文章

js 删除两个数组中id相同的对象
image.png

你可能感兴趣的:(ES6 数组内对象去重)