JS数组去重

使用 Set

Set 是 ES6 引入的数据结构,它只允许存储唯一值,因此可以通过将数组转换为 Set 来实现去重。

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

使用 filter 和 indexOf

通过 filter 方法遍历数组并使用 indexOf 来检查元素的第一次出现位置,保留那些位置与当前索引相同的元素。

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

使用 reduce 和 includes

使用 reduce 方法遍历数组并逐步构建一个不包含重复元素的新数组。

const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = array.reduce((accumulator, item) => {
  if (!accumulator.includes(item)) {
    accumulator.push(item);
  }
  return accumulator;
}, []);
console.log(uniqueArray);  // 输出: [1, 2, 3, 4]

使用 forEach 和 includes

使用 forEach 方法遍历数组,同时构建一个新的数组,只有当元素不在新数组中时才将其添加进去。

const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = [];
array.forEach(item => {
  if (!uniqueArray.includes(item)) {
    uniqueArray.push(item);
  }
});
console.log(uniqueArray);  // 输出: [1, 2, 3, 4]

使用 Map

通过 Map 来记录元素的出现次数,从而构建一个不包含重复元素的数组。

const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = array.sort().reduce((acc, item) => {
  if (acc.length === 0 || acc[acc.length - 1] !== item) {
    acc.push(item);
  }
  return acc;
}, []);
console.log(uniqueArray);  // 输出: [1, 2, 3, 4]

使用 sort 和 reduce

首先对数组进行排序,然后使用 reduce 方法遍历,过滤掉相邻的重复元素。

const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = array.sort().reduce((acc, item) => {
  if (acc.length === 0 || acc[acc.length - 1] !== item) {
    acc.push(item);
  }
  return acc;
}, []);
console.log(uniqueArray);  // 输出: [1, 2, 3, 4]

以上就是数组去重的几种方法,欢迎大家评论补充

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值