求star

开源不易,喜欢请点个star吧

Ocean Han
240 字
1 分钟
数组去重常用方法
2022-08-05

一、数组去重#

①利用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
}, [])

数组去重常用方法
https://blog.oceanh.top/posts/frontend/数组去重的常用方法/
作者
Ocean Han
发布于
2022-08-05
许可协议
CC BY-NC-SA 4.0
最后修改时间
2024-08-10 10:08:49