मान लीजिए हमारे पास नंबर्स का दो-आयामी ऐरे है:
const arr = [ [1, 3, 2], [5, 2, 1, 4], [2, 1] ];
हमें एक जावास्क्रिप्ट फंक्शन लिखना है जो सभी समान नंबर्स को उनके अपने अलग सबऐरे में ग्रुप करे, और फिर फंक्शन को ग्रुप ऐरे को सॉर्ट करके सबऐरे को बढ़ते क्रम में रखना चाहिए।
इसलिए, अंत में नया ऐरा ऐसा दिखना चाहिए:
const output = [ [1, 1, 1], [2, 2, 2], [4], [3], [5] ];
उदाहरण
इसके लिए कोड:
const arr = [ [1, 3, 2], [5, 2, 1, 4], [2, 1] ]; const groupAndSort = arr => { const res = []; const map = Object.create(null); Array.prototype.forEach.call(arr, item => { item.forEach(el => { if (!(el in map)) { map[el] = []; res.push(map[el]); }; map[el].push(el); }); }); res.sort((a, b) => { return a[0] - b[0]; }); return res; }; console.log(groupAndSort(arr));आउटपुट
कंसोल में आउटपुट:
[ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3 ], [ 4 ], [ 5 ] ]