js数组去重(4种方法)

1.使用 js 中的 filter 和 indexOf 来进行数组去重
// 示例数组
let array = [1, 2, 3, 1, 2, 4, 5, 3];

// 使用 filter 和 indexOf 进行去重

let uniqueArray = array.filter((value, index, self) => {
    // 返回第一次出现的索引位置,若当前索引与第一次出现的索引相同,则保留该元素
    return self.indexOf(value) === index;
});

console.log(uniqueArray); // 输出去重后的数组 [1, 2, 3, 4, 5]
2.使用 Set 数据结构
let array = [1, 2, 3, 1, 2, 4, 5, 3];

let uniqueArray = [...new Set(array)];

console.log(uniqueArray); // 输出去重后的数组 [1, 2, 3, 4, 5]
3.reduce
let array = [1, 2, 3, 1, 2, 4, 5, 3];

let uniqueArray = array.reduce((acc, currentValue) => {

    if (acc.indexOf(currentValue) === -1) {  // 这里检查当前值在累加器(acc)中是否不存在
        acc.push(currentValue);  // 如果不存在,就将其添加到累加器中
    }
    return acc;  // 返回更新后的累加器

}, []);  // 初始时,累加器为空数组

console.log(uniqueArray); // 输出去重后的数组 [1, 2, 3, 4, 5]
4.map
  • 首先创建了一个 Map 对象 map 。
  • 然后通过 for...of 循环遍历输入的数组 array 。
  • 对于每个元素 item ,检查 map 中是否已经存在该元素(通过 map.has(item) )。如果不存在,就使用 map.set(item, true) 将其添加到 map 中。由于 Map 的键是唯一的,所以重复的元素不会被再次添加。
  • 最后,使用 Array.from(map.keys()) 将 map 的键提取出来并转换为一个新的数组 uniqueArray ,从而实现了数组的去重。
let array = [1, 2, 3, 1, 2, 4, 5, 3];

let map = new Map();

for (let item of array) {  // 遍历数组中的每个元素
    if (!map.has(item)) {  // 如果 Map 中不存在当前元素
        map.set(item, true);  // 将当前元素作为键,值为 true 存入 Map 中,利用 Map 键的唯一性来实现去重
    }
}

let uniqueArray = Array.from(map.keys());  // 将 Map 的键转换为数组
 
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值