编辑
2021-07-05
undefined
00
请注意,本文编写于 1169 天前,最后修改于 28 天前,其中某些信息可能已经过时。

目录

参考 数组对象去重

数据如下:

js
[{ name: 'zs', age: 15 }, { name: 'lisi' }, { name: 'zs' }]

想要将 name 为 zs 的数据去重,优先保留第一条相同数据

解决方法

reduce 去重

js
let 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

lodash 工具库去重

Lodash Documentation

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]

想要所有对象属性都一样才去重也简单

js
var 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 许可协议。转载请注明出处!