Giả sử chúng ta có mảng sau:
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 }
]Chúng ta cần đếm số lần xuất hiện của các tên trùng lặp. Kết quả mong đợi:
John: 3, David: 2, Bob: 1
Sử dụng phương thức reduce().
Ví dụ
Mã minh họa:
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);Để chạy chương trình, sử dụng lệnh:
node tenFile.js
Tên file ở đây là demo282.js.
Kết quả
Đầu ra trên console:
PS C:\Users\Amit\javascript-code> node demo282.js
[ { studentName: 'John', occurrences: 3 }, { studentName: 'David', occurrences: 2 }, { studentName: 'Bob', occurrences: 1 } ]