DAY 6
0
Software Development

# 陣列切割 (Chunk)

Example:

input1
function chunk([1,2,3,4,5], 2)

output1
[[1,2],[3,4], 5]
-----------------------
input2
function chunk([1,2,3,4,5,6,7,8,9], 3)

output2([[1,2,3],[4,5,6],[7,8,9]])

## JavaScript 解法

function chunk(qArray, size) {
const mainAry = []

for(let el of qArray){
const subAry = mainAry[mainAry.length -1]

if(!subAry || subAry.length === size){
mainAry.push([el])
} else {
subAry.push(el)
}

}
console.log(mainAry)

return mainAry;

}

### JavaScript 解法 2

Array.prototype.slice() 方法挑出子陣列 (subAry)，再放到主陣列(mainAry)

function chunk2(array, size) {
const mainAry = [];
let index = 0;

while (index < array.length) {
let subAry = array.slice(index, index + size)
mainAry.push(subAry);
index = index + size;
}

return mainAry;
}

## Java 解法

public class Solution {

private <T> List<List<T>> chunk(List<T> members, int maxSize) {
List<List<T>> mainAry = new ArrayList<>();

List<T> subAry = new ArrayList<>();

for (T member : members) {

if (subAry.size() == maxSize) {
subAry = new ArrayList<>();
}
}
if (!subAry.isEmpty()) {
}
return mainAry;
}

public static void main(String[] args) {
Solution sol = new Solution();