有多种实现方式:

一、使用 Set 对象:

Array.from(new Set(array))

该方法会先创建一个 Set 对象,然后再使用 Array.from 方法将 Set 对象转换为数组,因为 Set 对象不允许有重复的元素,所以这样可以实现去重的效果。

但是,如果数组中的元素是对象,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);
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。