让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
当前回答
我是这样解决的:
const chunks = [];
const chunkSize = 10;
for (let i = 0; i < arrayToSplit.length; i += chunkSize) {
const tempArray = arrayToSplit.slice(i, i + chunkSize);
chunks.push(tempArray);
}
其他回答
# in coffeescript
# assume "ar" is the original array
# newAr is the new array of arrays
newAr = []
chunk = 10
for i in [0... ar.length] by chunk
newAr.push ar[i... i+chunk]
# or, print out the elements one line per chunk
for i in [0... ar.length] by chunk
console.log ar[i... i+chunk].join ' '
如果你正在使用下划线JS,只需使用:
var result = _.chunk(arr,elements_per_chunk)
无论如何,大多数项目已经使用下划线作为依赖项。
我认为这是ES6语法的一个很好的递归解决方案:
Const chunk =函数(数组,大小){ If (!array.length) { 返回[]; } Const head = array。片(0,大小); Const tail = array.slice(size); 返回[头,…块(尾巴,大小)]; }; 块console.log(((1、2、3),2));
在JS,
const splitInChunks = (arr,n) => {
let chunksArr = [];
if(arr !=null && arr!= undefined){
for(i=0; i<arr.length;i+=n){
if(arr.length-i>=n)
chunksArr.push(arr.slice(i,i+n))
else
chunksArr.push(arr.slice(i,arr.length))
}
return chunksArr
}
}
整洁干净,易于理解
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let len = nums.length ;
const chunkArr = (arr, chunkNo) => {
let newArr = [];
for(let i = 0; i < len; i++){
if(nums[0] !== "" && nums[0] !== undefined ){
let a = nums.splice(0,chunkNo) ;
newArr.push(a);
}
}
return newArr ;
}
console.log(chunkArr(nums, 5));