js中数组去重(数组中元素是对象)

一、使用 Set 对象: 

const arr = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' },
    { id: 1, name: 'A' },
    { id: 3, name: 'C' }
];

const result = Array.from(new Set(arr.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
console.log(result);

二、使用`reduce`方法:

const arr = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' },
    { id: 1, name: 'A' },
    { id: 3, name: 'C' }
];
const result = arr.reduce((pre, cur) => {
    var exists = pre.find(item => JSON.stringify(item) === JSON.stringify(cur));
    if (!exists) {
        pre.push(cur);
    }
    return pre;
}, []);
console.log(result);

 三、使用`filter`方法

const arr = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' },
    { id: 1, name: 'A' },
    { id: 3, name: 'C' }
];
const result =arr.filter((item, index, self) => {
    return self.findIndex(t => JSON.stringify(t) === JSON.stringify(item)) === index;
});
console.log(result);

你可能感兴趣的:(javascript,前端,vue.js)