There is a great question on how to split a JavaScript array into chunks. I'm currently using this for some statistical methods I'm writing and the answer that I'm using is as follows (although I chose not to extend the Array prototype like they did in the answer):
var chunk = function(array, chunkSize) {
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
};
This takes an array, such as [1,2,3,4,5,6]
, and given a chunkSize
of 2 returns [[1,2],[3,4],[5,6]]
. I'm curious how I could modify this to create an array of "overlapping" chunks (or for those familiar with methods such as a moving average, "moving subgroups").
Provided the same array as above and chunkSize
of 3, it would return [[1,2,3],[2,3,4],[3,4,5],[4,5,6]]
. A chunkSize
of 2 would return [[1,2],[2,3],[3,4],[4,5],[5,6]]
.
Any thoughts on how to approach this?
var array = this;
in order to use it in your for loop for the prototype extension. Second, this is very close, but not quite. Given[1,2,3,4,5,6]
, it returns[[1,2],[2,3],[3,4],[4,5]]
. Changing the max value fori
fromarray.length - chunkSize
toarray.length - chunkSize/2
fixed this problem though. Thanks for this! – Timotheus