Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...