JavaScript:Array数组去重

单数组

1.利用Array.from(new Set)去重:
let list = [1,2,3,4,5,5,5,6]
let newList = Array.from(new Set(list))
console.log('newList >> ', newList);
2.利用includes去重
let list = [1,2,3,4,5,5,5,6]
let newList = []
list.forEach((item) => {
    if (!newList.includes(item)) {
        newList.push(item)
    }
})
console.log('newList >>> ', newList)
3.利用map去重
let list = [1,2,3,4,5,5,5,6]
let newList = []
let map = new Map()
list.forEach((item) => {
   if (!map.has(item)) {
       map.set(item, ture)
       newList.push(item)
   }
})
console.log('newList >>> ', newList)
4.利用indexOf去重
let list = [1,2,3,4,5,5,5,6]
let newList = []
let map = new Map()
list.forEach((item) => {
    if (newList.indexOf(item) === -1) {
        newList.push(item)
    }
})
console.log('newList >>> ', newList)
5. 利用单层for循环去重
let list = [1,2,3,4,5,5,5,6]
for (let i = 0; i < list.sort().length; i++) {
    if (list[i] == list[i + 1]) {
        list.splice(i, 1)
        i--
    }    
}
console.log('newList >>> ', list)
6.利用双层for循环去重
let list = [1,2,3,4,5,5,5,6]
for (let i = 0; i < list.sort().length; i++) {
    for (let j = i + 1; j < list.sort().length; j++) {
        if (list[i] == list[j]) {
            list.splice(i, 1)
            j--
        }    
    }
}
console.log('newList >>> ', list)
 7.利用递归去重
let list = [1,2,3,4,5,5,5,6]
function callBack(index) {
    if (index >= 1) {
        if (list[index] === list[index - 1]) {
            list.splice(index, 1)
        }
        callBack(index - 1)
    }
}
callBack(list.sort().length - 1)
console.log('newList >>> ', list)

对象数组 

1.利用Array.filter和map去重
function nonRepet(list, key) {
    return list.filter((item) => !map.has(item[key].toString()) && map.set(item[key].toString()))
}

console.log('newList >>> ', nonRepet(list, 'id'));
2.利用Array.filter和Array.includes 去重
function nonRepet(list, key) {
    let list = [];
    return arr.filter((item) => !list.includes(item.name) && list.push(item.name)
}

console.log('newList >>> ', nonRepet(list, 'id'));
3.判断否重复值
let newArray = new Set();
list.filter(function(item, index, array) {
   newArray.add(item.name)
});

if(newArray.size !=  list.length){
    console.log("有重复值");
}

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值