在 JavaScript 中將陣列拆分為組
我們需要編寫一個 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' ] ]
廣告