javascript - 从数组中获取唯一 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
,然后找到length
or size
?
解决方案
您可以使用.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)
推荐阅读
- javascript - 图表,如何使用日期作为 xAxis 添加数据
- r - ggplotly 不会重现大小图例
- excel - 分隔字符串并仅显示第一个值
- resultset - Laravel meilisearch 列优先级
- java - 如何使用 Selenium 和 Java 从输出控制台或输出文本文件中提取特定字符串
- ubuntu - 在 Ubuntu 20.04 上安装 kubectl 并没有在 /usr/kubernetes/ 中创建任何 .conf 文件
- android - 片段中的Android ListView - 获取新数据后刷新表的问题
- semantic-release - GitHub - 使用 PR 中所有提交的语义发布版本说明
- php - Gitlab CI 上的“错误 [语义错误] 属性中的注释“@Doctrine\ORM\Mapping\OnetoMany””,但在本地环境或生产中没有
- javascript - 如何在 AJAX 回调中转换我的图表数据创建