目录
对于这个问题,需要考虑到各种情况的数组
const arr1 = [1, 1, 1, 1, 1, 2, 2, 2, 3];
const arr2 = [1, 1, 1, 'a', 'b', 'a', 2, 2];
const arr3 = [{
a: 1 }, {
a: 1 }, {
b: 2 }, {
b: 2 }, {
c: 3 }];
const arr4 = [1, , , , 2, , 3];
const arr5 = [true, true, false, true, false];
Set + Array.from 去重法
利用 ES6 新增的数据结构 Set,是一个独一无二的值的集合
function unique(arr){
return Array.from(new Set(arr));
}
或者用扩展运算符,更简单
function unique(arr){
return [...new Set(arr)];
}
遍历数组下标去重法
思路:数组的下标来表示这个元素的唯一性,我们以indexOf()
来返回第一次出现的位置,如果发现它不是当前自己的位置,就说明这个元素是重复的。
实现:遍历数组,查找每一个元素的indexOf()
位置,如果位置等于自己的位置,就把这个唯一值放进新数组。或者,当新数组中没有找到该元素(返回值为-1),就把这个元素放进去。
function unique(arr) {
// 新数组
let res = [];
// 遍历原数组
for (let index = 0; index < arr.length; index++) {
// 判断:当前位置元素的下标 是否等于 当前位置
if (arr.indexOf(arr[index]) == index) {
res.push(arr