JavaScript 数组去重方法大全

前言 在开发 JavaScript 应用程序时,经常遇到需要对数组进行去重的情况。 方法一:使用 Set 数据 […]

前言

在开发 JavaScript 应用程序时,经常遇到需要对数组进行去重的情况。

方法一:使用 Set 数据结构

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

方法一利用 JavaScript 中的 Set 数据结构的特性,通过将数组转换为 Set,再将 Set 转换回数组的方式实现去重。

方法二:使用 filter() 方法

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

方法二使用了 JavaScript 数组的 filter() 方法,通过筛选出数组中第一次出现的元素来实现去重。

方法三:使用 reduce() 方法

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

方法三使用了 JavaScript 数组的 reduce() 方法,通过遍历数组并将不重复的元素添加到累加器中来实现去重。

版权声明
文章标题:JavaScript 数组去重方法大全
文章链接:https://blog.chiyuba.com/qianduanjishu/540.html
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,转载或引用请注明出处。
温馨提示:本文最后更新于 2023年6月29日,部分内容可能存在时效性,请注意甄别。

相关推荐

更多教程
Qt QTableView setData的坑 UI相关 Qt QTableView setData的坑

前言 最近在使用QTableView的时...

25 浏览
ThinkPHP8报错:Command “build“ is not defined. 前端技术 ThinkPHP8报错:Command “build“ is not defined.

  简介:报错信息[Inval...

18 浏览
谷歌浏览器插件开发之打开一个新的tab页面 前端技术 谷歌浏览器插件开发之打开一个新的tab页面

前言 今天给大家分享: 谷歌浏览器插件开...

21 浏览

评论