สมมติว่าต่อไปนี้คืออาร์เรย์ของเรา –
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 }
]