js数组去除重复

1.

let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result = arr.sort().reduce((init, current)=>{
    if(init.length===0 || init[init.length-1]!==current){
        init.push(current);
    }
    return init;
}, []);
console.log(result); //[1,2,3,4,5]

2. 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++) {
if (arr[i] === arr[j]) {
j = ++i;
}
}
result.push(arr[i]);
}
return result;
}

3.使用set集合给元素去重复,一行代码解决问题

[...new Set(arr2)]

Array.from(new Set(arr2))

4.json数组和arry去重复通用

function unque4(arr){

for(var i = 0;i<arr.length;i++){

for(var j =i+1;j<arr.length;){

if(arr[i]==arr[j]){

arr.splice(j,1)

}else{

j++;

}

}

}

return arr;

}

posted @ 2018-07-10 14:02  江山一族  阅读(203)  评论(0编辑  收藏  举报