Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 数组对象去重

作者:忽然之间   发布日期:2026-07-28   浏览:30

// 示例代码:js 数组对象去重

// 假设我们有一个包含重复对象的数组
const arr = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' }, // 重复项
  { id: 3, name: 'Charlie' }
];

// 方法一:使用 Set 和 map 来去重(基于某个唯一键,如 id)
function uniqueBy(arr, key) {
  const seen = new Set();
  return arr.filter(item => {
    const value = item[key];
    return seen.has(value) ? false : seen.add(value);
  });
}

const uniqueArr = uniqueBy(arr, 'id');
console.log(uniqueArr);
// 输出: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }]

// 方法二:使用 reduce 和 findIndex 来去重(基于整个对象的比较)
function uniqueObjects(arr) {
  return arr.reduce((acc, current) => {
    const x = acc.find(item => JSON.stringify(item) === JSON.stringify(current));
    if (!x) {
      return acc.concat([current]);
    } else {
      return acc;
    }
  }, []);
}

const uniqueArr2 = uniqueObjects(arr);
console.log(uniqueArr2);
// 输出: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }]

解释说明:

  1. 方法一

    • 使用 Set 来存储已经遇到的键值(例如 id),并通过 filter 方法过滤掉重复的对象。
    • 这种方法适用于你有一个唯一的标识符(如 id)来判断对象是否重复。
  2. 方法二

    • 使用 reduce 方法遍历数组,并通过 find 方法检查当前对象是否已经在结果数组中存在。
    • 如果不存在,则将其添加到结果数组中;否则跳过。
    • 这种方法适用于你需要基于整个对象的内容来进行去重的情况。注意这种方法可能会有性能问题,因为它需要对每个对象进行字符串化比较。

上一篇:js 对象数组去重

下一篇:js 数组转对象

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站