हमें एक जावास्क्रिप्ट फ़ंक्शन लिखने की आवश्यकता है जो शाब्दिक और एक संख्या की एक सरणी लेता है और सरणी (पहला तर्क) को प्रत्येक लंबाई 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' ] ]