How to create windowed slice of array in JavaScript?

后端 未结 3 1609
旧时难觅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:34

    Here you go with a slightly shorter example using array functions:

    let a = [1, 2, 3, 4, 5, 6];
    function windowedSlice(arr, size) {
      let result = [];
      arr.some((el, i) => {
        if (i + size >= arr.length) return true;
        result.push(arr.slice(i, i + size));
      });
      return result;
    }
    console.log(windowedSlice(a, 2));
    console.log(windowedSlice(a, 3));
    console.log(windowedSlice(a, 4));
    console.log(windowedSlice(a, 5));

提交回复
热议问题