1

I want to split an array in even (or as even as possible) chunks. The input of the function should be the array and the size of the chunks. Say you have the array

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]

If you put it in the function below, with 5 as chunk size, it will result in the following

[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]

However, I want the result to be

[[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]

Which means sacrificing the length of the arrays before to make them only differ one in length.

The function I'm currently using is stated below. I've tried various things with modulo but I can't figure it out.

function chunkArray(myArray, chunkSize){
var arrayLength = myArray.length;
var tempArray = [];

for (index = 0; index < arrayLength; index += chunkSize) {
    myChunk = myArray.slice(index, index+chunkSize);
    // Do something if you want with the group
    tempArray.push(myChunk);
}

return tempArray;

}

Darshan
  • 35
  • 1
  • 4
Arno
  • 59
  • 1
  • 4

3 Answers3

1

With this solution you get evenly split array items until the last item which incorporates any left over items (collection of items that's length is less than the chunk size.)

const a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
const chunk = 4

const chunk_array = (a, c) => {
  let arr = []
  
  a.forEach((_, i) => {
    if (i%chunk === 0) arr.push(a.slice(i, i+chunk))
  })
  
  const [left_overs] = arr.filter(a => a.length < chunk)
  
  arr = arr.filter(a => a.length >= chunk)
  
  arr[arr.length-1] = [...arr[arr.length-1], ...left_overs] 
  
  return arr
}

console.log(
  chunk_array(a, chunk)
)
Francis Leigh
  • 1,870
  • 10
  • 25
-1

You could check with a modulo if your array length is odd :

let MY_CHUNK_CONST = 5
let first_chunk_size = MY_CHUNK_CONST,
other_chunk_size = MY_CHUNK_CONST;
let myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
modulo_res = myArray.length % 2; // 0 if even 1 if odd

if(modulo_res){
 other_chunk_size = first_chunk_size - 1;
}

var tempArray = [];

myChunk = myArray.slice(0, 0+first_chunk_size);
tempArray.push(myChunk);
for (index = 1; index < myArray.length; index += other_chunk_size) {
    myChunk = myArray.slice(index, index+other_chunk_size);
    // Do something if you want with the group
    tempArray.push(myChunk);
}

console.log(tempArray)
// [[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]

Hope it helps.

Flo
  • 936
  • 1
  • 8
  • 19
-1

My solution!

const chunk = (arr, chunkSize) => {
  let chunked = [];
  for (let i = 0; i< arr.length; i+=chunkSize){
    chunked.push(
      arr.slice(i, (i + chunkSize))
    );
  }

  return chunked;
};

const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];

console.log(chunk(data, 5));
// returns [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]]
StefanN
  • 871
  • 6
  • 19
  • 5 in OP is just an example number, he don't want to make 5 chunk. OP want to create equal number of chunks based on array size. – ravibagul91 Jul 05 '19 at 14:31