js数组去重
1.indexOf去重
function unqueArray (arr) {
let unqueArray = arr.filter(function(elem, index, self) {
return index == self.indexOf(elem);
})
return unqueArray;
}
unqueArray([1,2,3,4,5,4,55,3,2,1,4]); // [1, 2, 3, 4, 5, 55]
2.new Set()去重
Array.from(new Set([1,2,3,4,5,4,55,3,2,1,4])); // [1, 2, 3, 4, 5, 55]
3.对象去重
function unqueArray(arr){
let obj = {};
let result = [];
arr.forEach(item =>{
if(!obj[item]){
obj[item] = true;
result.push(item)
}
})
return result;
}
unqueArray([0,0,0,1,2,2,5,4,4,8,5,6]); // [0, 1, 2, 5, 4, 8, 6]
4.循环去重
Array.prototype.unqueArray = function(){
let arr = this;
let result = [];
let len = 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;
}
let data = [1,2,3,4,6,5,4,8,6,5,4];
data.unqueArray(); //返回 [1,2,3,8,6,5,4]
5.递归排序
先排序会递归碰到一样的进行删除即可
Array.prototype.unqueArray = function (){
let arr = this;
let len = arr.length;
arr.sort(function(a,b){
return a - b;
})
function loop(index){
if(index >= 1){
if(arr[index] === arr[index-1]){
arr.splice(index,1);
}
loop(index - 1);
}
}
loop(len-1);
return arr;
};
let data = [5,3,2,7,45,3,234,5,4];
data.unqueArray();
// [2, 3, 4, 5, 7, 45, 234]