मान लीजिए हमारे पास ऐसा ऐरे है:
const arr = [
{unit: 35, brand: 'CENTURY'},
{unit: 35, brand: 'BADGER'},
{unit: 25, brand: 'CENTURY'},
{unit: 15, brand: 'CENTURY'},
{unit: 25, brand: 'XEGAR'}
];
हमें एक फंक्शन लिखना है जो उन सभी ब्रैंड प्रॉपर्टीज़ को ग्रुप करता है जिनके ऑब्जेक्ट्स की unit प्रॉपर्टी समान है।
उपरोक्त ऐरे के लिए, नया ऐरे होना चाहिए:
const output = [
{unit: 35, brand: 'CENTURY, BADGER'},
{unit: 25, brand: 'CENTURY, XEGAR'},
{unit: 15, brand: 'CENTURY'}
];
हम ऐरे पर लूप करेंगे, एक हेल्पर फंक्शन का उपयोग करके unit मान वाले ऑब्जेक्ट को खोजेंगे। अगर यह मौजूद है, तो हम ब्रैंड मान को जोड़ देंगे अन्यथा एक नया ऑब्जेक्ट बनाएंगे।
उदाहरण
निम्नलिखित कोड है:
const arr = [
{unit: 35, brand: 'CENTURY'},
{unit: 35, brand: 'BADGER'},
{unit: 25, brand: 'CENTURY'},
{unit: 15, brand: 'CENTURY'},
{unit: 25, brand: 'XEGAR'}
];
const indexOf = function(unit){
return this.findIndex(el => el.unit === unit)
};
Array.prototype.indexOf = indexOf;
const groupArray = arr => {
const res = [];
for(let i = 0; i < arr.length; i++){
const ind = res.indexOf(arr[i].unit);
if(ind !== -1){
res[ind].brand += `, ${arr[i].brand}`;
}else{
res.push(arr[i]);
}
};
return res;
};
console.log(groupArray(arr));
आउटपुट
यह कंसोल में निम्नलिखित आउटपुट देगा:
[
{ unit: 35, brand: 'CENTURY, BADGER' },
{ unit: 25, brand: 'CENTURY, XEGAR' },
{ unit: 15, brand: 'CENTURY' }
]