方法一:
双层循环,外层循环元素,内层循环时比较值
如果有相同的值则跳过,不相同则push进数组
let arr = [10, 20, 3, 88, 11, 88, 3, 20, 10, 22, 35];
Array.prototype.distinct = function () {
var _arr = this,
result = [],
i,
j,
len = _arr.length;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
console.log(_arr[i], _arr[j]);
if (_arr[i] === _arr[j]) {
j = ++i;
}
}
result.push(_arr[i]);
}
return result;
};
let _distinctArr = arr.distinct();
console.log(_distinctArr); //输出结果:[11, 88, 3, 20, 10, 22, 35]
方法二:利用splice直接在原数组进行操作
双层循环,外层循环元素,内层循环时比较值
值相同时,则删去这个值
注意点:删除元素之后,需要将数组的长度也减1.
let arr = [10, 20, 3, 88, 11, 88, 3, 20, 10, 22, 35];
Array.prototype.distinct = function () {
var _arr = this,
i,
j,
len = _arr.length;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
if (_arr[i] == _arr[j]) {
_arr.splice(j, 1);
len--;
j--;
}
}
}
return _arr;
};
let _distinctArr = arr.distinct();
console.log(_distinctArr); //输出结果 [11, 88, 3, 20, 10, 22, 35]
方法三:数组递归去重(结合indexOf())
运用递归的思想
从数组末端开始对比,结合indexOf(),如果元素出现的位置和当前位置不相等则删去
let arr = [10, 20, 3, 88, 11, 88, 3, 20, 10, 22, 35];
Array.prototype.distinct = function () {
var _arr = this,
len = _arr.length;
function loop(index) {
if (index >= 0) {
if (_arr.indexOf(_arr[index]) != index) {
_arr.splice(index, 1);
}
loop(index - 1); //递归loop函数进行去重
}
}
loop(len - 1);
return _arr;
};
let _distinctArr = arr.distinct();
console.log(_distinctArr); //输出结果 [10, 20, 3, 88, 11, 22, 35]
方法四:filter
filter 过滤首次出现和当前位置相等的元素
let arr = [10, 20, 3, 88, 11, 88, 3, 20, 10, 22, 35];
Array.prototype.distinct = function () {
var _arr = this;
return _arr.filter((f, index) => _arr.indexOf(f) == index);
};
let _distinctArr = arr.distinct();
console.log(_distinctArr); //输出结果:[11, 88, 3, 20, 10, 22, 35]
方法五:利用ES6的set
Set数据结构,它类似于数组,其成员的值都是唯一的。
利用Array.from将Set结构转换成数组
let arr = [10, 20, 3, 88, 11, 88, 3, 20, 10, 22, 35];
Array.prototype.distinct = function () {
var _arr = this;
return Array.from(new Set(_arr));
};
let _distinctArr = arr.distinct();
console.log(_distinctArr); //输出结果:[11, 88, 3, 20, 10, 22, 35]
拓展运算符(...)内部使用for...of循环
let arr = [10, 20, 3, 88, 11, 88, 3, 20, 10, 22, 35];
Array.prototype.distinct = function () {
var _arr = this;
return [...new Set(_arr)];
};
let _distinctArr = arr.distinct();
console.log(_distinctArr); //输出结果:[11, 88, 3, 20, 10, 22, 35]
方法六:includes(indexOf)
定义一个新的数组,遍历原数组,利用includes(indexOf)检测是否存在,如不存在则加入
let arr = [10, 20, 3, 88, 11, 88, 3, 20, 10, 22, 35];
Array.prototype.distinct = function () {
var _arr = this;
var newArr = [];
for (var i = 0; i < _arr.length; i++) {
if (!newArr.includes(arr[i])) {
//includes 检测数组是否有某个值, 亦可以使用(indexOf(arr[i] < 0))
newArr.push(arr[i]);
}
}
return newArr;
};
let _distinctArr = arr.distinct();
console.log(_distinctArr); //输出结果:[11, 88, 3, 20, 10, 22, 35]