ধরুন, আমাদের কাছে এই ধরনের বস্তুর একটি অ্যারে আছে −
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
]; আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা বস্তুগুলিকে আলাদা অ্যারে অফ অ্যারেতে বিভক্ত করে যেগুলির uuid সম্পত্তির জন্য একই মান রয়েছে৷
আউটপুট
অতএব, আউটপুট এইরকম হওয়া উচিত -
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 } ]
]