js 数组,对象数组去重的多种方法

在JavaScript中,数组去重(尤其是对象数组去重)是一个常见的需求。这里提供几种不同的方法来实现数组去重,包括简单数组和对象数组的去重。

1. 简单数组去重

使用 Set

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
使用 filter
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index, self) => {
    return self.indexOf(item) === index;
});
console.log(uniqueArray); // [1, 2, 3, 4, 5]

2. 对象数组去重

对象数组去重通常依赖于对象的某个或某些属性来判断是否重复。

使用 filter 和 findIndex
const objects = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 1, name: 'Alice' }, // 重复
    { id: 3, name: 'Charlie' }
];

const uniqueObjects = objects.filter((obj, index, self) => {
    return self.findIndex(t => (
        t.id === obj.id
    )) === index;
});

console.log(uniqueObjects);
// [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]

使用 Map

Map 的键是唯一的,因此可以用来去重。

const objects = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 1, name: 'Alice' }, // 重复
    { id: 3, name: 'Charlie' }
];

const uniqueObjects = Array.from(new Map(objects.map(obj => [obj.id, obj])).values());

console.log(uniqueObjects);
// [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]

注意,上面的 Map 方法基于 id 属性去重,保留了第一个出现的对象。

使用 reduce

reduce 方法同样可以实现去重。

const objects = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 1, name: 'Alice' }, // 重复
    { id: 3, name: 'Charlie' }
];

const uniqueObjects = objects.reduce((acc, current) => {
    const isExist = acc.some(item => item.id === current.id);
    if (!isExist) {
        acc.push(current);
    }
    return acc;
}, []);

console.log(uniqueObjects);
// [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]

总结

  • 对于简单数组去重,Set 是最简单且性能最好的方法。
  • 对于对象数组去重,通常需要根据对象的某个或某些属性来判断是否重复,可以使用 filter + findIndex、Map、或 reduce 等方法来实现。
  • 在选择去重方法时,应考虑代码的清晰性、可维护性和性能。对于大型数组,应优先考虑性能较好的方法。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值