[TOC] #### 1. 前言 --- 本文提供两个数组变量供测试使用 ```javascript const array = ['html', 'css', 'js', 'css'] const resArr = ['html', 'css', 'css', [1], [1]] ``` #### 2. 普通方法数组去重 --- 下面列举几种数组去重的方法思路都一样: 遍历数组,将数组元素添加到新数组中,新数据中已有该元素,则不添加到新数组 ```javascript // for + indexOf const res = []; for (let index = 0; index < array.length; index++) { res.indexOf(array[index]) === -1 && res.push(array[index]) } // forEach + indexOf const res = []; array.forEach(item => { res.indexOf(item) === -1 && res.push(item) }) // reduce + includes const res = array.reduce((total, item) => { !total.includes(item) && total.push(item) return total; }, []) ``` #### 3. filter + indexOf --- 使用 `filter + indexOf` 的方式可以使代码变为更简洁 `filter()` 方法过滤数组,只保留满足条件的元素。`indexOf()` 方法判断元素首次出现的下标是否为当前遍历的下标 ```javascript // ['html', 'css', 'js'] const res = array.filter((item, index) => array.indexOf(item) === index) ``` #### 4. ES6 的 new Set() --- 利用 Set 结构不能接收重复数据的特点 ```javascript const res = [...new Set(array)] ``` #### 5. 需要注意的问题 --- 当数组中存在引用类型的元素时,引用类型元素无法保持唯一性 ```javascript const resArr = ['html', 'css', 'css', [1], [1]] // ['html', 'css', 'css', [1], [1]] const res = resArr.filter((item, index) => resArr.indexOf(item) === index) ```