0

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

0

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.