-
千秋此意
function chunk(arr, size) {
for(var i=0,newArray=[],temp=[]; i<Math.ceil(arr.length/size); i++){
for(var j=0;j<size;j++){
temp[j] = (arr[j+i*size]);
}
newArray[i] = [].concat(temp.includes(undefined) ? temp.slice(0, temp.indexOf(undefined)) : temp);
}
return newArray;
}
console.log(chunk([1,2,3,4,5,6,233,233], 3)); // => [ [1,2,3], [4,5,6], [233,233] ]
-
_潇潇暮雨
function chunk(arr, size) {
for(var i=0,newArray=Array();i<Math.ceil(arr.length/size);i++){
newArray[i] = Array();
for(var j=0;j<size;j++){
newArray[i].push(arr[j+i*size]);
}
}
return newArray;
}
var arr = [1,2,3,4,5,6,7,8,9,0];
var size = 3;
var ret = chunk(arr,size);
console.log(ret);
-
慕函数0307879
function chunk(arr, size) { for(var i=0,newArray=Array();i<Math.ceil(arr.length/size);i++){ newArray[i] = Array(); for(var j=0;j<size;j++){ newArray[i].push(arr[j+i*size]); } } var p=0; for(var k=0;k<newArray[newArray.length-1].length;k++){ if(newArray[newArray.length-1][k]!=null){ p++; } } for(var l=0;l<size-p;l++){ newArray[newArray.length-1].pop(); } return newArray;}楼上回答的代码有些缺陷,如果被分割的数组元素不满size时,会填充null进数组。需要消除null才能算是正确答案。我这么写的代码肯定很难看,不过基本的任务完成了,看楼主如何自行简化代码吧
-
文森特_
function chunk(arr, size) { // Break it up. var arr1 = []; for (var i = 0; i < arr.length; i = i + size) { var arr2 = arr; arr1.push(arr2.slice(i, i + size)); } return arr1;}chunk(["a", "b", "c", "d"], 2);