हमें एक JavaScript फंक्शन लिखना है जो लिटरल के ऐरे और एक नंबर को लेता है और ऐरे (पहला आर्गुमेंट) को n (दूसरा आर्गुमेंट) लंबाई के ग्रुप में विभाजित करता है और इस प्रकार बने दो-आयामी ऐरे को लौटाता है।
यदि ऐरे और नंबर है:
const arr = ['a', 'b', 'c', 'd']; const n = 2;
तो आउटपुट होना चाहिए:
const output = [['a', 'b'], ['c', 'd']];
उदाहरण
आइए अब कोड लिखते हैं:
const arr = ['a', 'b', 'c', 'd'];
const n = 2;
const chunk = (arr, size) => {
const res = [];
for(let i = 0; i < arr.length; i++) {
if(i % size === 0){
// Push a new array containing the current value to the res array
res.push([arr[i]]);
}
else{
// Push the current value to the current array
res[res.length-1].push(arr[i]);
};
};
return res;
};
console.log(chunk(arr, n));
आउटपुट
कंसोल में आउटपुट होगा:
[ [ 'a', 'b' ], [ 'c', 'd' ] ]