嗨,我想按给定的数量分割数组。
arr = [0,1,2,3,4,5,6,7,8,9,10]
$scope.arraySpliter(arr);
$scope.arraySpliter = function (a) {
var arrays = [], size = 3;
var tempCount = Math.ceil(a.length / 3);
while (a.length > 0)
arrays.push(a.splice(0, tempCount));
console.log(arrays);
};
我想要这样的拆分数组。 [0,1,2,3] [4,5,6,7] [8,9,10]
答案 0 :(得分:1)
这是一种递归方法:
const splitIn = count => arr => {
if (count < 2) {return [arr]}
const first = Math.ceil(arr.length / count);
return [arr.slice(0, first)].concat(splitIn(count - 1)(arr.slice(first)))
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(splitIn(3)(arr))
这将产生前四个(ceiling(10 / 3)
)元素作为其第一组,然后将其余六个元素递归地分为两组。当我们开始分成一个组时,它只是将其包装在一个数组中。