如何计算 JavaScript 中对象数组中重复名称的出现次数?
给定一个对象数组,任务是根据其值查找给定键的出现。
例子:
Input : arr = [
{
employeeName: "Ram",
employeeId: 23
},
{
employeeName: "Shyam",
employeeId: 24
},
{
employeeName: "Ram",
employeeId: 21
},
{
employeeName: "Ram",
employeeId: 25
},
{
employeeName: "Kisan",
employeeId: 22
},
{
employeeName: "Shyam",
employeeId: 20
}
]
key = "employeeName"
Output: [
{employeeName: "Ram", occurrences: 3},
{employeeName: "Shyam", occurrences: 2},
{employeeName: "Kisan", occurrences: 1}
]
为了实现这一点,我们有以下方法:
方法一:
在这种方法中,我们遵循以下步骤。
- 创建一个空的输出数组。
- 使用 forEach 迭代输入数组。
- 检查输出数组是否包含任何包含提供的键值的对象
- 如果不是,则创建一个新对象并初始化该对象,其中键(提供的键名)设置为值(当前迭代的对象的键值)并将发生设置为值 1
- 如果是,则迭代输出数组并搜索当前迭代的键是否等于输入数组迭代的键,然后将出现次数增加到 1。
Javascript
输出:
[
{
employeeName: "Ram",
occurrence: 3
},
{
employeeName: "Shyam",
occurrence: 2
},
{
employeeName: "Kisan",
occurrence: 1
}
]