मान लीजिए हमारे पास ऑब्जेक्ट्स का ऐरे है:
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 } ] ]