मान लीजिए, हमारे पास ऐसा 2-D ऐरे है:
const arr = [ [3, 1], [2, 12], [3, 3] ];
हमें एक JavaScript फ़ंक्शन लिखना है जो ऐसा ऐरे लेता है।
फ़ंक्शन को फिर एक नया 2-D ऐरे बनाना चाहिए जिसमें इनपुट ऐरे में मौजूद एलिमेंट के इंडेक्स के अलावा सभी एलिमेंट्स undefined से इनिशियलाइज़ हों।
इसलिए, इनपुट ऐरे के लिए:
output[3][1] = 1; output[2][12] = 1; output[3][3] = 1;
और बाकी सभी एलिमेंट्स undefined से इनिशियलाइज़ होने चाहिए।
इसलिए, अंतिम आउटपुट इस तरह दिखना चाहिए:
const output = [ undefined, undefined, [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 1 ], [ undefined, 1, undefined, 1 ] ];
उदाहरण
इसके लिए कोड होगा:
const arr = [ [3, 1], [2, 12], [3, 3] ]; const map2D = (arr = []) => { const res = []; arr.forEach(el => { res[el[0]] = res[el[0]] || []; res[el[0]][el[1]] = 1; }); return res; }; console.log(map2D(arr));आउटपुट
कंसोल में आउटपुट होगा:
[ <2 empty items>, [ <12 empty items>, 1 ], [ <1 empty item>, 1, <1 empty item>, 1 ] ]