js实现数组去重常用且推荐的几种方法

数组去重常见的5种方法

  1. 使用 Set
  2. 使用 filterindexOf
  3. 使用 reduceincludes
  4. 使用 forEachObject
  5. 使用 Map

总结(推荐方法)

1、使用Set推荐

Set 是 ES6 引入的集合类型,类似于数组,但其成员都是唯一的。这使得 Set 成为数组去重的一个非常简洁和高效的工具。

实现步骤:
  1. 将数组转换为 Set,自动去除重复的值。
  2. 将 Set 再转换回数组。
代码示例:
let array = [1, 2, 3, 4, 4, 3, 2, 1];
let uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4]
解析:
  • new Set(array):创建一个 Set,自动去除数组中的重复值。
  • [...new Set(array)]:使用扩展运算符 … 将 Set 再转换为数组。

2、使用 filterindexOf

filter 是数组的方法,用于过滤数组元素。indexOf 是数组的方法,用于返回某个指定元素在数组中首次出现的位置。

实现步骤:
  1. 使用 filter 遍历数组。
  2. 在每次遍历时,用 indexOf 检查当前元素在数组中的第一次出现的位置。
  3. 如果当前元素的索引等于它第一次出现的位置,则保留该元素,否则过滤掉。
代码示例:
let array = [1, 2, 3, 4, 4, 3, 2, 1];
let uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // [1, 2, 3, 4]
解析:
  • array.filter((item, index) => ...):遍历数组,对每个元素执行一次提供的函数。
  • array.indexOf(item):查找当前元素在数组中第一次出现的位置。
  • array.indexOf(item) === index:如果当前元素在数组中第一次出现的位置等于当前索引,则保留该元素。

3、使用 reduceincludes

使用 reduce 方法和 includes 方法去重。

let array = [1, 2, 3, 4, 4, 3, 2, 1];
let uniqueArray = array.reduce((acc, item) => {
  if (!acc.includes(item)) {
    acc.push(item);
  }
  return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4]

4、使用 forEachObject

使用 forEach 方法和对象的键值对去重。

let array = [1, 2, 3, 4, 4, 3, 2, 1];
let obj = {};
array.forEach(item => {
  obj[item] = true;
});
let uniqueArray = Object.keys(obj).map(Number);
console.log(uniqueArray); // [1, 2, 3, 4]

5、使用 Map

使用 Map 数据结构来去重。

let array = [1, 2, 3, 4, 4, 3, 2, 1];
let map = new Map();
array.forEach(item => {
  if (!map.has(item)) {
    map.set(item, true);
  }
});
let uniqueArray = [...map.keys()];
console.log(uniqueArray); // [1, 2, 3, 4]

总结(推荐方法)

  • Set 去重 简单、高效,适合大多数场景。
  • filterindexOf 去重 更为灵活,可以添加额外的条件或逻辑,但相对较慢,因为每次 filter 迭代都要执行一次 indexOf 查找。

推荐使用 Set 进行数组去重,因为这种方法最简洁、性能较好,并且代码可读性高。其他方法在某些特定场景下也可能会有用,可以根据具体需求选择合适的方法。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值