如何计算数组中重复名称的出现次数-JavaScript?
假设以下是我们的数组-
var details = [ { studentName: "John", studentAge: 23 }, { studentName: "David", studentAge: 24 }, { studentName: "John", studentAge: 21 }, { studentName: "John", studentAge: 25 }, { studentName: "Bob", studentAge: 22 }, { studentName: "David", studentAge: 20 } ]
我们需要计算重复名称的出现次数,即输出应为
John: 3 David: 2 Bob: 1
为此,您可以使用的概念reduce()
。
示例
以下是代码-
var details = [ { studentName: "John", studentAge: 23 }, { studentName: "David", studentAge: 24 }, { studentName: "John", studentAge: 21 }, { studentName: "John", studentAge: 25 }, { studentName: "Bob", studentAge: 22 }, { studentName: "David", studentAge: 20 } ] var output = Object.values(details.reduce((obj, { studentName }) => { if (obj[studentName] === undefined) obj[studentName] = { studentName: studentName, occurrences: 1 }; else obj[studentName].occurrences++; return obj; }, {})); console.log(output);
要运行以上程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo282.js。这将在控制台上产生以下输出-
PS C:\Users\Amit\javascript-code> node demo282.js [ { studentName: 'John', occurrences: 3 }, { studentName: 'David', occurrences: 2 }, { studentName: 'Bob', occurrences: 1 } ]