使用Set進行數組去重
function unrepeaty(param){
let set = new Set(param)
// 這裏輸出的是set數據類型
console.log(set) // Set { 1, 2, 3, 33, 'ys' }
// 可以通過展開運算符來轉換會數組
console.log([...set]) // [ 1, 2, 3, 33, 'ys' ]
// Array.from將可迭代對象轉換成數組
let arr = Array.from(set)
return arr
}
let arr = [1,2,3,33,1,3,'ys','ys']
unrepeaty(arr) // [ 1, 2, 3, 33, 'ys' ]
使用reduce進行數組去重
function unrepeaty(param){
let reduce = param.reduce((pre,cur) => {
// 判斷當前pre數組裏面是否有了重複的數據
if(pre.indexOf(cur) == -1){
pre.push(cur)
}
return pre
},[])
return reduce
}
let arr = [1,2,3,33,1,3,'ys','ys']
unrepeaty(arr) // [ 1, 2, 3, 33, 'ys' ]
使用filter進行數組去重
function unrepeaty(param){
let filter = param.filter((item,index) => {
// 判斷item的下標是否是第一次出現下標,如果是true則返回
return param.indexOf(item) === index
})
return filter;
}
let arr = [1,2,3,33,1,3,'ys','ys']
unrepeaty(arr) // [ 1, 2, 3, 33, 'ys' ]