# 《前端算法系列》数组去重

## 前言

``````module.exports = async function getFnRunTime(fn) {
let startTime = Date.now(), endTime;
let result = await fn();
endTime = Date.now();
console.log(`total time:\${endTime-startTime}ms`,
'test array\'length:' + len,
result.length
);
}

## 1.双重for循环去重

``````function distinct1(arr = testArr) {
let result = [],
len = arr && arr.length;
for (let i=0; i< len; i++) {
for (let j=i+1; j< len; j++) {
if (arr[i] === arr[j]) {
j = ++i;
}
}
result.push(arr[i])
}
return result
}

## 2.利用indexOf和forEach/for循环去重

``````function distinct2(arr = testArr) {
let result = [];
arr.forEach((v, i, array) => {
array.indexOf(v, i+1) === -1 && result.push(v)
});
return result
}

## 3.对象法

``````function distinct3(arr = testArr) {
let result = [], resultObj = {}, len = arr.length;
for(let i=0; i< len; i++) {
let val = arr[i],
type = typeof val;
if(!resultObj[val]) {
result.push(val);
resultObj[val] = [type];
} else if(!resultObj[val].indexOf(type) < 0) {
result.push(val);
resultObj[val] = [type];
}
}
return result
}

## 4.filter去重方法一

``````function distinct4(arr = testArr) {
return arr.filter((v, i, array) => array.indexOf(v, i+1) < 0)
}

## 5.filter去重方法二

``````function distinct5(arr = testArr) {
return arr.filter((v, i, array) => array.indexOf(v) === i)
}

## 6.利用es6的set方法

``````function distinct6(arr = testArr) {
return [...new Set(arr)]
}