js 数组去重

Posted on 2021-02-04 15:40  zkx4213  阅读(41)  评论(0编辑  收藏  举报

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

Copyright © 2024 zkx4213
Powered by .NET 8.0 on Kubernetes