Three practical methods for deduplication of objects in ES6 arrays

In actual projects, it is inevitable to encounter duplication of elements in the array. The following will introduce several methods for deduplication of ES6 arrays:

1. Use Set to deduplicate

const arr = ['张三','张三','三张三']
let set = new Set(arr); // set 自带去重
// Set { '张三', '三张三' }
console.log(set);
console.error(Array.from(set)); // [ '张三', '三张三' ]

2. Use reduce to deduplicate

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. Use reduceRight to deduplicate and reverse the order of the array

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

 Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/131559150