乐趣区

关于html5:js-对象数组-去重


去重 函数 unique

function unique(arr, key) {if (!arr) return arr
    if (key === undefined) return [...new Set(arr)]
    const map = {'string': e => e[key],
        'function': e => key(e),
    }
    const fn = map[typeof key]
    const obj = arr.reduce((o,e) => (o[fn(e)]=e, o), {})
    return Object.values(obj)
}

一般数组去重

unique([1, 1, 1, 14, 1, 4, 4, 1, 13])

对象数组 去重

const list = [{ id: 0,    name: '小明',    age: 13},
    {id: 1,    name: '小明',    age: 99},
    {id: 2,    name: '小明',    age: 23},
    {id: 3,    name: '小红',    age: 42},
    {id: 4,    name: '小明',    age: 13},
    {id: 5,    name: '小芳',    age: 35},
    {id: 0,    name: '小明',    age: 13},
    {id: 7,    name: '',    age: 23},
    {id: 8,    name: 'lm',    age: 22},
    {id: 9,    name: 'xh',    age: 79}
]

unique(list, 'id')    // id 去重
unique(list, 'age') // age 去重
unique(list, 'name')    // name 去重
unique(list, e => e.name + e.age)    // name+age 去重

实现 hashcode 去重

function hashcode(str) {str = typeof str === 'object' ? JSON.stringify(str) : str
    var hash = 0, i, chr, len;
    if (str.length === 0) return hash;
    for (i = 0, len = str.length; i < len; i++) {chr   = str.charCodeAt(i);
        hash  = ((hash << 5) - hash) + chr;
            hash |= 0; // Convert to 32bit integer
    }
    return hash;
}

unique(list, e => hashcode(e))        // hashcode 去重 


退出移动版