Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into overlapping chunks (moving subgroups)

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?

like image 380
mbeasley Avatar asked Oct 04 '22 23:10

mbeasley


1 Answers

function chunk (array, chunkSize) {
    var retArr = [];
    for (var i = 0; i < array.length - (chunkSize - 1); i++) {
        retArr.push(array.slice(i, i + chunkSize));
    }
    return retArr;
}

If you did want to extend the prototype (probably would be better) it would looks like this:

Array.prototype.chunk = function( chunkSize ) {
    var retArr = [];
    for (var i = 0; i < this.length - (chunkSize - 1); i++) {
        retArr.push( this.slice(i, i + chunkSize));
    }
    return retArr;
}
like image 57
gbtimmon Avatar answered Oct 10 '22 03:10

gbtimmon