参考 数组对象去重
数据如下:
js[{ name: 'zs', age: 15 }, { name: 'lisi' }, { name: 'zs' }]
想要将 name 为 zs 的数据去重,优先保留第一条相同数据
jslet hash = {}
function unique(arr, initialValue) {
return arr.reduce(function (previousValue, currentValue, index, array) {
hash[currentValue.name] ? '' : (hash[currentValue.name] = true && previousValue.push(currentValue))
return previousValue
}, initialValue)
}
const uniqueArr = unique([{ name: 'zs', age: 15 }, { name: 'lisi' }, { name: 'zs' }], [])
console.log(uniqueArr) // uniqueArr.length == 2
js_.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x')
// => [{ 'x': 1 }, { 'x': 2 }]
// 指定条件
_.uniqBy([2.1, 1.2, 2.3], Math.floor)
// => [2.1, 1.2]
想要所有对象属性都一样才去重也简单
jsvar objects = [
{ x: 1, y: 2 },
{ x: 2, y: 1 },
{ x: 1, y: 2 },
]
_.uniqWith(objects, _.isEqual)
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
本文作者:任浪漫
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明出处!