让我们说我有一个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个元素?
当前回答
下面是一个使用reduce的ES6版本
const perChunk = 2 //每个chunk有2个项目 const inputArray = ['a','b','c','d','e'] const result = inputArray。reduce((resultArray, item, index) => { const chunkIndex = Math.floor(index/perChunk) 如果(! resultArray [chunkIndex]) { resultArray[chunkIndex] =[] //启动一个新的chunk } resultArray [chunkIndex] .push(项) 返回resultArray }, []) console.log(结果);// result: [['a','b'], ['c','d'], ['e']]]
并且您已经准备好连接进一步的映射/缩减转换。 输入数组保持不变
如果你喜欢更短但可读性较差的版本,你可以在混合中添加一些concat,以获得相同的最终结果:
inputArray.reduce((all,one,i) => {
const ch = Math.floor(i/perChunk);
all[ch] = [].concat((all[ch]||[]),one);
return all
}, [])
你可以使用余数运算符将连续的项放入不同的块中:
const ch = (i % perChunk);
其他回答
这个问题可能有很多解决方案。
我最喜欢的一个是:
function chunk(array, size) { const chunked = []; for (element of array){ let last = chunked[chunked.length - 1]; if(last && last.length != size){ last.push(element) }else{ chunked.push([element]) } } return chunked; } function chunk1(array, size) { const chunked = []; let index = 0; while(index < array.length){ chunked.push(array.slice(index,index+ size)) index += size; } return chunked; } console.log('chunk without slice:',chunk([1,2,3,4,5,5],2)); console.log('chunk with use of slice funtion',chunk1([1,2,3,4,5,6],2))
# 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 ' '
我更喜欢使用splice方法:
var chunks = function(array, size) {
var results = [];
while (array.length) {
results.push(array.splice(0, size));
}
return results;
};
这里是一个仅使用递归和slice()的非突变解决方案。
const splitToChunks = (arr, chunkSize, acc = []) => (
arr.length > chunkSize ?
splitToChunks(
arr.slice(chunkSize),
chunkSize,
[...acc, arr.slice(0, chunkSize)]
) :
[...acc, arr]
);
然后简单地像splitToChunks([1,2,3,4,5], 3)一样使用它来获得[[1,2,3],[4,5]]。
这里有一个小提琴供你尝试:https://jsfiddle.net/6wtrbx6k/2/
现在你可以使用lodash的chunk函数将数组分割成更小的数组https://lodash.com/docs#chunk不再需要摆弄循环了!