240 字
1 分钟
数组去重常用方法
一、数组去重
①利用ES6的Set
类:milky_way:
let arr = [1,4,5,6,1,3,2,,9,9,5,7,3]
let noRepeat = [...new Set(arr)]
②利用filter
去重:milky_way:
let arr = [1,4,5,6,1,3,2,,9,9,5,7,3]
let noRepeat = arr.filter((item,index)=>{
return arr.indexOf(item) === index
})
③利用indexOf
方法
let arr = [1,4,5,6,1,3,2,,9,9,5,7,3]
function noRepeat(arr) {
let newArr = []
for(let i=0;i<arr.length;i++){
if(newArr.indexOf(arr[i]) === -1){
newArr.push(arr[i])
}
}
return newArr
}
let newArr = noRepeat(arr)
④利用includes
方法
let arr = [1,4,5,6,1,3,2,,9,9,5,7,3]
function noRepeat(arr) {
let newArr = []
for(let i=0;i<arr.length;i++){
if(!newArr.includes(arr[i])){
newArr.push(arr[i])
}
}
return newArr
}
let newArr = noRepeat(arr)
⑤双重循环遍历
WARNING 复杂度太高,不推荐
二、数组对象去重
let arr = [{
id: '1',
key: '1',
value: '明月'
}, {
id: '3',
key: '2',
value: '可欣'
}, {
id: '2',
key: '3',
value: '小红'
}, {
id: '1',
key: '1',
value: '小馨'
}, {
id: '1',
key: '2',
value: '小静'
}]
①Map
方法
let map = new Map()
for(let item of arr){
map.set(item.id,item)
}
arr = [...map.values()]
②对象访问属性
let newArr = [];
let obj = {};
for (var i = 0; i < arr.length; i++) {
if (!obj[arr[i].key]) {
newArr.push(arr[i])
obj[arr[i].key] = true
}
}
③reduce
方法
const obj = {}
arr = arr.reduce((total, next) => {
obj[next.key] ? '' : obj[next.key] = true && total.push(next)
return total
}, [])