-3

I am trying to wrap my head around the following:

We have the following example array: var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

We have user input N as a parameter.

For the sake of this example, let's assume that N = 3.

After that, let's define the var blockSize = 2 * N

The example array arr then has to be split into chunks like these:

[0, 0, 0, 1, 2, 3], [1, 2, 3, 4, 5, 6], [4, 5, 6, 7, 8, 9], [7, 8, 9, 10, 11, 12], [10, 11, 12, 0, 0 ,0]

Note that this is a perfect example where numbers get split perfectly because of the parameter we gave. I need this to be working even with cases, where it won't be so perfect. In that case, zeros should be added to the end of the last chunk to have it properly sized (N*2).

vohilDev
  • 1
  • 1
  • 1
    Does this answer your question? [Split array into chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks) – Aplet123 Dec 26 '20 at 14:41
  • @Aplet123 No, it doesn't. Partially, but not what I need to implement. Hence why I asked a new one. The article you've linked is simply slicing the array which is one part of my agorithm. I have a problem with repeating the previous values when creating a new chunk. – vohilDev Dec 26 '20 at 14:44

1 Answers1

-1

You can slice in a loop:

function overlappingChunks(arr, len) {
    const chunks = [];
    for (let i = 0; i < arr.length; i += len) {
        const chunk = arr.slice(i, i + len * 2);
        chunks.push(chunk.concat(new Array(len * 2  - chunk.length).fill(0)));
    }
    return chunks;
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55