问题很简单。我有一个数组,比如
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
maxChunkLength = 3;
我需要将它拆分为多个数组,以获得:
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]
请注意,块的最后一个元素应该是它旁边的块的第一个元素。
有人知道最好的方法吗?
答案 0 :(得分:4)
此功能可能适合您,
function splitArray(array, chunk){
var i,j, rslt = [];
chunk = chunk - 1;
for (i=0,j=array.length; i<j; i+=chunk) {
rslt.push(array.slice(i,i+chunk +1));
}
return rslt;
}
实施例
splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); //[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]
答案 1 :(得分:1)
这大约是接受答案的两倍。
function chunk(arr, chunkSize) {
var curr = [], result = [], i, j;
for (i=0, j=arr.length; i<j; i++) {
curr.push(arr[i]);
if (curr.length === chunkSize) {
result.push(curr);
curr = [arr[i]];
}
}
if (curr.length !== chunkSize) {
result.push(curr);
}
return result;
}
document.write(JSON.stringify(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)));
答案 2 :(得分:0)
这对你有用吗?
var originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var maxChunkLength = 3
var newArray = [];
for (var i = 0; i < originalArray.length; maxChunkLength += 2) {
var tempArray = [];
for (var j = i; j < i+maxChunkLength; j++) {
if (typeof originalArray[j] !== "undefined") {
tempArray.push(originalArray[j]);
}
}
newArray.push(tempArray);
tempArray = [];
}
答案 3 :(得分:0)
这应该有效,
var arr = [1,2,3,4,5,6,7,8];
var el1 = 0, el2 = 0, el3 = 0;
var result = [];
var splitLength = 3;
for(var i = 0; i < arr.length; i += (splitLength -1) ) {
var tempArr = [];
for(var j = 0; j < splitLength && arr[i+j]; j++) {
tempArr.push(arr[i+j]);
}
result.push(tempArr);
}
console.log("[" + result.join("]\n[") + "]");