मान लीजिए, हमारे पास एक JSON सरणी है जिसमें कुछ टिकटों के बारे में डेटा है जैसे -
const arr = [
{
"quantity": "1",
"description": "VIP Ticket to Event"
},
{
"quantity": "1",
"description": "VIP Ticket to Event"
},
{
"quantity": "1",
"description": "VIP Ticket to Event"
},
{
"quantity": "1",
"description": "Regular Ticket to Event"
},
{
"quantity": "1",
"description": "Regular Ticket to Event"
},
];
हमें एक JavaScript फ़ंक्शन लिखना है जो ऐसी एक सरणी लेता है। फ़ंक्शन को समान ऑब्जेक्ट को एक साथ समूहित करना चाहिए और उनके quantity प्रॉपर्टी को जोड़ना चाहिए।
दो ऑब्जेक्ट को समान माना जाएगा यदि उनके "description" प्रॉपर्टी के लिए समान मान हैं।
उदाहरण
इसके लिए कोड होगा -
const arr = [
{
"quantity": "1",
"description": "VIP Ticket to Event"
},
{
"quantity": "1",
"description": "VIP Ticket to Event"
},
{
"quantity": "1",
"description": "VIP Ticket to Event"
},
{
"quantity": "1",
"description": "Regular Ticket to Event"
},
{
"quantity": "1",
"description": "Regular Ticket to Event"
},
];
const groupAndAdd = arr => {
const res = [];
arr.forEach(el => {
if (!this[el.description]) {
this[el.description] = {
description: el.description, quantity: 0
};
res.push(this[el.description]);
};
this[el.description].quantity += +el.quantity;
}, {});
return res;
}
console.log(groupAndAdd(arr));
आउटपुट
कंसोल में आउटपुट होगा -
[
{ description: 'VIP Ticket to Event', quantity: 3 },
{ description: 'Regular Ticket to Event', quantity: 2 }
]