-1

I have an array of map points that contain speeds and I want to create a new array of every 25 points and push them into another array called chunks. So this is what I am doing:

var chunks = []; // the array of chunks
var tempArray = []; //used for storing current chunk
var currentLoop = 0; //used for checking how many items have been taken
for (var i = 0; i < gon.map_points.length; i++) {
    if (currentLoop == 26) { // if the current items stored is above 25
        chunks.push(tempArray); // push the chunk
        currentLoop = 0; // reset the count
        tempArray = []; // reset the chunk
    }
    tempArray.push(gon.map_points[i].speed); // add item into chunk
    currentLoop++; // increase count
}

So this works fine unless the array of map points isn't a perfect number of points (e.g. it might be 117), so then I won't get the last 17 points added to my chunks array.

Is there a way to chunk up the array into 25 points regardless of the total items?

Cameron
  • 27,963
  • 100
  • 281
  • 483

2 Answers2

1

You could use Array#slice and an index and count up by the size, you need.

var array = Array.apply(null, { length: 65 }).map(function (_, j) { return j; }),
    chunks = [],
    chunkSize = 25,
    i = 0;

while (i < array.length) {
    chunks.push(array.slice(i, i + chunkSize));
    i += chunkSize;
}

console.log(chunks);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

you can use splice to set the chunks like this

var s = [];
var result = [];
function generate(){
 for(var i=0 ; i< 117; i++){
   s.push(i);
 }
}
generate();
//console.log(s)

while(s.length > 25){
  //console.log(s.splice(0,25))
  result[result.length] = s.splice(0,25);
}

result[result.length] = s;

console.log(result);
Vinod Louis
  • 4,812
  • 1
  • 25
  • 46