JavaScript:对象数组去重 (Array<object>)

4,959 阅读2分钟

网上有很多对象数组去重的方式,看得眼都花了,最后总结了其中以下四种本人认为较为常用,简洁的方式。

/** 示例数据 */
const arr = [ 
    { id: 1, name: 'Tom' }, 
    { id: 2, name: 'Jerry' },
    { id: 3, name: 'Tom' }, 
    { id: 4, name: 'Jerry' } 
];

1.传统遍历方式

使用for或者Array.forEach遍历,代码如下:

function uniqueArr(arr) {
  let result = []; 
  arr.forEach((item) => {
    if (!result.some(m => m.name === item.name)) {
      result.push(item);
    }
  });
  return result;
}

console.log(uniqueArr(arr)); // => [{ id: 1, name: 'Tom' }, { id: 2, name: 'Jerry' }]

上面的代码定义一个变量result来存储去重结果,在遍历过程中,判断result里是否已存在同名的记录,没有的话就往result添加记录。

2.使用Set数据结构

使用Set数据结构可以很方便地对数组对象去重,代码如下:

const uniqueArr = Array.from(new Set(arr.map(item => item.name))).map(name => { 
    return arr.find(item => item.name === name); 
}); 

console.log(uniqueArr); // => [{ id: 1, name: 'Tom' }, { id: 2, name: 'Jerry' }]

上面的代码先通过map方法将数组对象中的某个属性提取出来,然后使用Set数据结构去重。最后再通过map方法将去重后的属性值与原数组中的对象进行匹配,获取去重后的对象数组。

温馨提示: Set数据结构是ES6新增的特性之一

3.使用filter方法

使用Array.filter方法也可以很方便地对数组对象进行去重,代码如下:

const uniqueArr = arr.filter((item, index, arr) => { 
    return arr.findIndex(t => t.name === item.name) === index; 
});

console.log(uniqueArr); // => [{ id: 1, name: 'Tom' }, { id: 2, name: 'Jerry' }]

上面的代码使用Array.filter方法遍历数组对象,通过findIndex方法获取当前对象的第一个索引位置,如果当前对象的索引位置与第一个索引位置相等,则保留该对象。最后返回去重后的对象数组。

4.使用reduce方法

使用Array.reduce方法可以很简洁地对数组对象进行去重,代码如下:

const uniqueArr = arr.reduce((prev, cur) => { 
    if (!prev.some(item => item.name === cur.name)) { 
        prev.push(cur); 
    } 
    return prev;
}, []);

console.log(uniqueArr); // => [{ id: 1, name: 'Tom' }, { id: 2, name: 'Jerry' }]

上面的代码使用Array.reduce方法遍历数组对象,如果当前对象的某个属性在之前的数组对象中不存在,则将当前对象添加到新的数组中。最后返回去重后的对象数组。