js将一个数组分成多个数组

2020-05-06  本文已影响0人  Gaochengxin

js将一个数组分成多个数组

1,将数组array分成长度为subGroupLength的小数组并返回新数组

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">function group(array, subGroupLength) {
let index = 0;
let newArray = [];
while(index < array.length) {
newArray.push(array.slice(index, index += subGroupLength));
}
return newArray;
}

2,例如:
var Array = [1,2,3,4,5,6,7,8,9,10,11,12];;
var groupedArray = group(Array, 6);
得到的groupedArray 数组为:
groupedArray[[1,2,3,4,5,6],[7,8,9,10,11,12]]</pre>

上一篇下一篇

猜你喜欢

热点阅读