Splitting nested array to multiple arrays in JavaScript

I have an array like below.

[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]

and I want array like this.

[[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]

here is my approach to get this.

chunk(result, size) {
    var finalResluts = result;    
    for(let j=0; j<result.length; j++){      
      var  k = 0, n = result[j].length;
        while (k < n) {
        finalResluts[j].push(result[j].slice(k, k += size));
        }
    }    
    return finalResluts;
}

console.log(chunk([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 3));

result showing as like below. what I am doing wrong here?

0: Array(8)
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
6: (3) [1, 2, 3]
7: (3) [4, 5, 6]

for reference here is stackblitz https://stackblitz.com/edit/typescript-rmzpby

Answer

The problem is that you initialize your finalResults to the input array results, thus the results are pushed into the original [1, 2, 3, 4, 5, 6] array.
What you need to do is create an empty array for each subArray of the input to populate later. Easiest to achieve with map function:

function chunk(result, size) {
    //for each subArray - create empty array
    var finalResluts = result.map(subArray => []);    
    for(let j=0; j<result.length; j++){      
      var  k = 0, n = result[j].length;
        while (k < n) {
        finalResluts[j].push(result[j].slice(k, k += size));
        }
    }    
    return finalResluts;
}

console.log(chunk([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 3));

Leave a Reply

Your email address will not be published. Required fields are marked *