首页 > 解决方案 > 从数组中获取唯一 ID 的总和

问题描述

我需要遍历一个对象数组并对唯一_id(s)的总数求和。想象一个如下所示的数据结构:

  [
      { firstName: "John",
        lastName: "Johnson",
        _id: 23
      },
      { firstName: "John",
        lastName: "Johnson",
        _id: 23
      },
      { firstName: "Mary",
        lastName: "Smith",
        _id: 24
      }
  ]

...对于上述数据集,我totalUniqueIDs应该是2.

如果我只是遍历一个数组并获得“_id”的总和,我会这样做:

let customersArray = docs.map(doc => doc._id);
let customersArrayLength = customersArray.length
console.log(customersArrayLength); // 3

这当然会给我3个结果。

在这种情况下,我将如何获得唯一_id(s) 的总和?我是否首先将 转换array为 a set,然后找到lengthor size

标签: javascriptarraysset

解决方案


您可以使用.map()获取数组ids并使用Set对其进行重复数据删除:

const data = [{
    firstName: "John",
    lastName: "Johnson",
    _id: 23
  },
  {
    firstName: "John",
    lastName: "Johnson",
    _id: 23
  },
  {
    firstName: "Mary",
    lastName: "Smith",
    _id: 24
  }
]

const result = [... new Set(data.map(({_id}) => _id))]

console.log(result.length)


推荐阅读