0

Below is the working code for dividing array into chunks. Please let me if you have any better solution for this.

    var a = [];
    for (var i = 0; i < 4500; i++) {
        a.push(i);
    }
    var ttt = {};
    var start = 0;
    var end = 999
    if (a.length > 999) {
        for (var i = 0; i < 4; i++) {
            ttt[i] = a.slice(start, end);
            start = end + 1;
    
            end = start + 999;
            console.log(start + ":" + end);
        }
    }
    console.log(a.length);
    console.log(ttt[1].length);
georg
  • 211,518
  • 52
  • 313
  • 390
Sandeep M
  • 248
  • 3
  • 6

1 Answers1

0

You could use Array#splice() instead of Array#slice() if you do not need the array anymore.

var a = [],
    ttt = {},
    i;
    
for ( i = 0; i < 4500; i++) {
    a.push(i);
}

i = 0;
while (a.length) {
    ttt[i++] = a.splice(0, 1e3);
}

document.write('<pre> ' + JSON.stringify(a, 0, 4) + '</pre>');
document.write('<pre> ' + JSON.stringify(ttt, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392