//1.new Set
var arr1 = [1,2,3,2,4,1]
console.log(Array.from(new Set(arr1)))
console.log([...new Set(arr1)])
//封装成函数
var arr1 = [1,2,3,2,4,1]
function unique(arr){
return [...new Set(arr)]
}
console.log(unique(arr1))
//2.indexOf
var arr2 = [1,2,3,2,4,1]
function unique(arr){
var brr = [];
for( var i = 0; i < arr.length; i++){
if( brr.indexOf(arr[i]) == -1){//不存在才添加
brr.push(arr[i])
}
}
return brr;
}
console.log(unique(arr2))
//3.sort
var arr3 = [1,2,3,2,4,1]
function unique(arr){
arr = arr.sort()//排序
var brr = [];
for( var i = 0; i < arr.length; i++){
if([arr[i]] != [arr[i-1]]){//每一项都比前一项大,才放每一项
brr.push(arr[i])
}
}
return brr;
}
console.log(unique(arr3))
JS 简单的数组去重方法
最新推荐文章于 2024-11-08 16:09:18 发布