我想将数组拆分为偶数(或尽可能多的)块。 函数的输入应为数组和块的大小。 说你有数组
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
如果将其放在下面的函数中(块大小为5),则会显示以下内容
[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]
但是,我希望结果是
[[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]
这意味着先牺牲数组的长度,使它们的长度仅相差一个。
我当前正在使用的功能如下所述。我已经尝试过以模为单位的各种方法,但是我无法弄清楚。
function chunkArray(myArray, chunkSize){
var arrayLength = myArray.length;
var tempArray = [];
for (index = 0; index < arrayLength; index += chunkSize) {
myChunk = myArray.slice(index, index+chunkSize);
// Do something if you want with the group
tempArray.push(myChunk);
}
return tempArray;
}
答案 0 :(得分:1)
使用此解决方案,您可以平均分割数组项,直到最后一个合并了所有剩余项的项(长度小于块大小的项的集合)。
const a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
const chunk = 4
const chunk_array = (a, c) => {
let arr = []
a.forEach((_, i) => {
if (i%chunk === 0) arr.push(a.slice(i, i+chunk))
})
const [left_overs] = arr.filter(a => a.length < chunk)
arr = arr.filter(a => a.length >= chunk)
arr[arr.length-1] = [...arr[arr.length-1], ...left_overs]
return arr
}
console.log(
chunk_array(a, chunk)
)
答案 1 :(得分:-1)
您可以用模来检查数组长度是否为奇数:
let MY_CHUNK_CONST = 5
let first_chunk_size = MY_CHUNK_CONST,
other_chunk_size = MY_CHUNK_CONST;
let myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
modulo_res = myArray.length % 2; // 0 if even 1 if odd
if(modulo_res){
other_chunk_size = first_chunk_size - 1;
}
var tempArray = [];
myChunk = myArray.slice(0, 0+first_chunk_size);
tempArray.push(myChunk);
for (index = 1; index < myArray.length; index += other_chunk_size) {
myChunk = myArray.slice(index, index+other_chunk_size);
// Do something if you want with the group
tempArray.push(myChunk);
}
console.log(tempArray)
// [[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]
希望有帮助。
答案 2 :(得分:-1)
我的解决方案!
const chunk = (arr, chunkSize) => {
let chunked = [];
for (let i = 0; i< arr.length; i+=chunkSize){
chunked.push(
arr.slice(i, (i + chunkSize))
);
}
return chunked;
};
const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
console.log(chunk(data, 5));
// returns [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]]