0


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("有重复值");
}

本文转载自: https://blog.csdn.net/yao_guai/article/details/135151841
版权归原作者 dingcho 所有, 如有侵权,请联系我们删除。

“JavaScript:Array数组去重”的评论:

还没有评论