मान लें कि निम्नलिखित हमारी सरणी है -
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
इसके लिए आप कम () की अवधारणा का उपयोग कर सकते हैं।
उदाहरण
निम्नलिखित कोड है -
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 }
]