数组去重的方法(js)

在JavaScript中,处理数组去重有多种方法。以下是一些常见的方法:

1. 使用Set

Set是ES6中引入的一种新的数据结构,类似于数组,但所有元素都是唯一的。利用Set可以非常简洁地去除数组中的重复项。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]

2. 使用filter方法

该方法可以遍历数组,并利用indexOf方法检查元素首次出现的位置,如果当前位置与首次出现的位置相同,则保留该元素。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]

3. 使用reduce方法

reduce方法可以累积数组中的值,结合indexOf或者一个辅助的Object/Map来确定一个元素是否已经被添加到结果数组。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, current) => {
    if (acc.indexOf(current) === -1) {
        acc.push(current);
    }
    return acc;
}, []);
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]

4. 使用对象或Map

利用对象或Map作为辅助数据结构,存储已经出现过的元素。这种方法在处理大型数组或数组项为复杂类型时特别有效。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueMap = new Map();
const uniqueArray = array.filter(item => !uniqueMap.has(item) && uniqueMap.set(item, true));
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]

5. 使用forEach与includes

这是另一个结合数组方法的例子,使用forEach来迭代数组,并通过includes检查新数组中是否已经包含了当前元素。

const array = [1, 2, 2, 3, 4, 4, 5];
let uniqueArray = [];
array.forEach(item => {
    if (!uniqueArray.includes(item)) {
        uniqueArray.push(item);
    }
});
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值