天天看點

JavaScript 數組去重——普通數組去重 vs 對象數組去重簡單數組去重對象數組去重

目錄

簡單數組去重

對象數組去重

簡單數組去重

function arrDistinct(arr){
    const newArr = new Set(arr);
    return [...newArr]
}
           

使用範例

let list = [1,2,2,3,4,4]
console.log(arrDistinct(list))
           

對象數組去重

function arrDistinctByProp(arr,prop){
    //隻傳回第一次出現的,重複出現的過濾掉
    return arr.filter(function(item,index,self){
        return self.findIndex(el=>el[prop]==item[prop])===index
    })
}
           

使用範例

let list = [
    {
        key:'1',
        name:'林青霞'
    },
    {
        key:'2',
        name:'張三豐'
    },
    {
        key:'1',
        name:'段譽'
    },
    {
        key:'1',
        name:'段譽'
    }
]

//通過name屬性去重
console.log(arrDistinctByProp(list,'name'))
           

繼續閱讀