With this:
Array.prototype.chunk = function ( n ) {
if ( !this.length ) {
return [];
}
return [this.slice(0, n)].concat(this.slice(n).chunk(n));
};
And then:
const splittendAns = ans.chunk(20);
With the last line you divide the array in chunks of length 20
.
Here an example as requested:
// Suppose I have this array
// I want to split this array in 5 length arrays
const array = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
];
Array.prototype.chunk = function ( n ) {
if ( !this.length ) {
return [];
}
return [this.slice(0, n)].concat(this.slice(n).chunk(n));
};
const splittedArray = array.chunk(5);
console.log(array);
console.log('-----');
console.log(splittedArray);
OUTPUT:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
-----
[ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15 ] ]