在 JavaScript 中對陣列進行分塊
我們需要編寫一個 chunk() 函式,它將陣列 arr 作為第一個引數,字串/數字文字 arr 作為第二個引數。
我們需要返回一個由 n 個子陣列組成的陣列,每個子陣列最多包含 arr.length / n 個元素。元素分佈應如下 -
第一個元素在第一個子陣列中,第二個在第二個子陣列中,第三個在第三個子陣列中,依此類推。當每個子陣列中只有一個元素,我們再次開始填充第一個子陣列的第二個元素。同樣,當所有子陣列只有兩個元素時,我們在第一個陣列中填充第三個元素,依此類推。
例如 −
// if the input array is: const input = [1, 2, 3, 4, 5, 6]; //then the output should be: const output = [ [1, 4], [2, 5], [3, 6] ];
讓我們編寫此函式的程式碼,我們將 Array.prototype.reduce() 方法應用於原始陣列以構造所需的陣列。程式碼如下 -
示例
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const chunk = (arr, size) => { return arr.reduce((acc, val, ind) => { const subIndex = ind % size; if(!Array.isArray(acc[subIndex])){ acc[subIndex] = [val]; } else { acc[subIndex].push(val); }; return acc; }, []); }; console.log(chunk(input, 4));
輸出
控制檯中的輸出將是 −
[ [ 1, 5, 9 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]
廣告