How to create windowed slice of array in JavaScript?

后端 未结 3 1629
旧时难觅i
旧时难觅i 2021-01-16 21:28

I\'m looking for an array method implementation named Array.window(n) that invoked on an array with parameter n, would give a contiguous overlappin

3条回答
  •  情书的邮戳
    2021-01-16 21:39

    Here is a simple rolling window function. Notice that we can determine the number of iterations based on array length minus the desired window size.

    /**
     * Produces a rolling window of desired length {w} on a 1d array.
     * 
     * @param {Array} a The 1d array to window.
     * @param {Number} w The desired window size.
     * @return {Array} A multi-dimensional array of windowed values.
     */
    function rolling(a, w) {
        let n = a.length;
        let result = [];
    
        if (n < w || w <= 0) {
            return result;
        }
    
        for (let i = 0; i < n - w + 1; i++) {
            result.push(a.slice(i, w + i));
        }
    
        return result;
    }
    
    let a = [1, 2, 3, 4, 5];
    console.log(JSON.stringify(rolling(a, 3)));
    

提交回复
热议问题