js 数组去重

var arr = [1,2,8,9,5,8,4,0,4];
/*
模拟: 原始数组:[1,2,8,9,5,8,4,0,4]
索引值:0,1,2,3,4,5,6,7,8
伪新数组:[1,2,8,9,5,8,4,0,4]
使用indexOf方法找到数组中的元素在元素在中第一次出现的索引值
索引值:0,1,2,3,4,2,6,7,6
返回前后索引值相同的元素:
新数组:[1,2,8,9,5,4,0]
*/
function unique( arr ){
// 如果新数组的当前元素的索引值 == 该元素在原始数组中的第一个索引,则返回当前元素
return arr.filter(function(item,index){
return arr.indexOf(item,0) === index;
});
}
console.log(unique(arr)); // 1, 2, 8, 9, 5, 4, 0

原文地址:https://www.cnblogs.com/zkx4213/p/14372944.html