मान लीजिए, हमारे पास इस तरह की वस्तुओं की एक सरणी है -
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
]; हमें एक जावास्क्रिप्ट फ़ंक्शन लिखना आवश्यक है जो वस्तुओं को अलग-अलग सरणी में विभाजित करता है जिसमें यूयूआईडी संपत्ति के समान मान होते हैं।
आउटपुट
इसलिए, आउटपुट इस तरह दिखना चाहिए -
const output = [
[
{"name": "toto", "uuid": 1111},
{"name": "titi", "uuid": 1111}
],
[
{"name": "tata", "uuid": 2222}
]
]; इसके लिए कोड होगा -
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
];
const groupByElement = arr => {
const hash = Object.create(null),
result = [];
arr.forEach(el => {
if (!hash[el.uuid]) {
hash[el.uuid] = [];
result.push(hash[el.uuid]);
};
hash[el.uuid].push(el);
});
return result;
};
console.log(groupByElement(arr)); आउटपुट
कंसोल में आउटपुट -
[
[ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
[ { name: 'tata', uuid: 2222 } ]
]