让我们说我有一个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个元素?
当前回答
试试这个:
var oldArray =[“香蕉”、“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”); var newArray = []; 而(oldArray.length) { 让start = 0; 让end = 10; newArray.push (oldArray。片(开始、结束)); oldArray。拼接(开始、结束); } console.log (newArray);
其他回答
纯javascript中的一行代码:
函数块(数组,大小){ 返回数组中。应用(0,{长度:Math.ceil(数组。长度/大小)})。Map ((_, index) =>数组。片(指数*大小,大小(指数+ 1)*)) } //下面将字母表中的字母按4进行分组 console.log(块(数组(26)[…]. map ((x, i) = > String.fromCharCode (+ 97), 4))
# 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 ' '
基于数组的ES6一行方法。原型缩减和推送方法:
const doChunk = (list, size) => list.reduce((r, v) =>
(!r.length || r[r.length - 1].length === size ?
r.push([v]) : r[r.length - 1].push(v)) && r
, []);
console.log(doChunk([0,1,2,3,4,5,6,7,8,9,10,11,12], 5));
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12]]
使用ES6的拼接版本
让[列表,chunkSize] =[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12、13、14、15),6]; list =[…数组(Math.ceil(list. ceil))length / chunkSize))]。map(_ => list.splice(0,chunkSize)) console.log(列表);
使用来自lodash的chunk
lodash.chunk(arr,<size>).forEach(chunk=>{
console.log(chunk);
})