ধরুন, আমাদের কাছে একটি অবজেক্ট অ্যারে আছে −
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 } ] ]