1032

Let's say that I have an Javascript array looking as following:

["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.

What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?

6

84 Answers 84

1 2
3
1

Recursive way

function chunk(array, chunk_size){
    if(array.length == 0) return [];
    else return [array.splice(0, chunk_size)].concat(chunk(array, chunk_size))
}

console.log(chunk([1,2,3,4,5,6,7,8],3))

1

Here is a simple solution, based on flatMap (I haven't see any in the existing answers):

function splitIntoChunks(array, chunkSize) {
  return array.flatMap((x, i) =>
    i % chunkSize === 0 ? [array.slice(i, i + chunkSize)] : []
  );
}
0
1

Another version using Array.reduce but without using Math object and remainder (%) operator:

const chunk = size => array => array.reduce((result, item) => {
  if (result[result.length - 1].length < size) {
    result[result.length - 1].push(item);
  } else {
    result.push([item]);
  }
  return result;
}, [[]]);

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log(chunk(3)(myArray)); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
console.log(chunk(4)(myArray)); // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

0
# in coffeescript
# assume "ar" is the original array
# newAr is the new array of arrays

newAr = []
chunk = 10
for i in [0... ar.length] by chunk
   newAr.push ar[i... i+chunk]

# or, print out the elements one line per chunk
for i in [0... ar.length] by chunk
   console.log ar[i... i+chunk].join ' '
0

I changed BlazeMonger's slightly to use for a jQuery object..

var $list = $('li'),
    $listRows = [];


for (var i = 0, len = $list.length, chunk = 4, n = 0; i < len; i += chunk, n++) {
   $listRows[n] = $list.slice(i, i + chunk);
}
0

Here's a solution using ImmutableJS, where items is an Immutable List and size is the required grouping size.

const partition = ((items, size) => {
  return items.groupBy((items, i) => Math.floor(i/size))
})
0

Her is a simple solution using @Blazemonger solution

function array_chunk(arr, size){
    // initialize vars
    var i,
    j = arr.length,
    tempArray = [];
    // loop through and jump based on size
    for (i=0; i<j; i+=size) {
        // slice chunk of arr and push to tempArray
        tempArray.push(arr.slice(i,i+size));
    }
    // return temp array (chunck)
    return tempArray
}

This got the pipline flowing for me, hope this helps someone else out there. :)

0

Here's another solution with the reduce() method, though slightly different from other examples. Hopefully my explanation is a bit clearer as well.

var arr = [0, 1, 2, 3, 4, 5, 6, 7];
var chunkSize = 3;

arr = arr.reduce((acc, item, idx) => {
  let group = acc.pop();
  if (group.length == chunkSize) {
    acc.push(group);
    group = [];
  }
  group.push(item);
  acc.push(group);
  return acc;
}, [[]]);

console.log(arr); //Prints [[0, 1, 2], [3, 4, 5], [6, 7]]


Explanation

We call a reducer which, for each item in the array, gets the last item of the accumulator with pop(). Remember that this item is an array which groups up to chunkSize number of items (3 in this example).

If, and only if, this group has the array length equal to chunksize we need to re-insert the group back into the accumulator and create a new group.

We then push the current item into our group array (which may already contain 0, 1 or 2 items from the previous steps). With the current item inserted into the group, we need to re-insert the group back into the larger collection.

The process will repeat until we've iterated through all items in arr.

Note that we have also provided the reducer with the starting value of an empty array inside an array with [[]].

0

I prefer to use the splice method instead of slice. This solution uses the array length and chunk size to create a loop count and then loops over the array which gets smaller after every operation due to splicing in each step.

    function chunk(array, size) {
      let resultArray = [];
      let chunkSize = array.length/size;
      for(i=0; i<chunkSize; i++) {
        resultArray.push(array.splice(0, size));
      }
    return console.log(resultArray);
    }
    chunk([1,2,3,4,5,6,7,8], 2);

If you dont want to mutate the original array, you can clone the original array using the spread operator and then use that array to solve the problem.

    let clonedArray = [...OriginalArray]
0

Try this :

var oldArray =  ["Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango"];

var newArray = [];

while(oldArray.length){
    let start = 0;
    let end = 10;
    newArray.push(oldArray.slice(start, end));
    oldArray.splice(start, end);
 }
 
 console.log(newArray);

0
0

my trick is to use parseInt(i/chunkSize) and parseInt(i%chunkSize) and then filling the array

// filling items
let array = [];
for(let i = 0; i< 543; i++)
  array.push(i);
 
 // printing the splitted array
 console.log(getSplittedArray(array, 50));
 
 // get the splitted array
 function getSplittedArray(array, chunkSize){
  let chunkedArray = [];
  for(let i = 0; i<array.length; i++){
    try{
      chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i];
    }catch(e){
      chunkedArray[parseInt(i/chunkSize)] = [];
      chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i];
    }
  }
  return chunkedArray;
 }

0

I solved it like this:

const chunks = [];
const chunkSize = 10;
for (let i = 0; i < arrayToSplit.length; i += chunkSize) {
  const tempArray = arrayToSplit.slice(i, i + chunkSize);
  chunks.push(tempArray);
}
0

Super late to the party but I solved a similar problem with the approach of using .join("") to convert the array to one giant string, then using regex to .match(/.{1,7}/) it into arrays of substrings of max length 7.

const arr = ['abc', 'def', 'gh', 'ijkl', 'm', 'nopq', 'rs', 'tuvwx', 'yz'];
const arrayOfSevens = arr.join("").match(/.{1,7}/g);
// ["abcdefg", "hijklmn", "opqrstu", "vwxyz"]

Would be interesting to see how this performs in a speed test against other methods

2
  • This doesn't serve the original purpose at all.
    – m4heshd
    Apr 5, 2021 at 11:16
  • It would perform quite poorly I'm afraid because of, first, Regexes then the join, I'd say.
    – gfache
    Apr 29, 2021 at 12:08
0

TypeScript version. Demonstrated is 101 random uid's split into groups of 10

const idArrayLengthLimit = 10;
const randomOneHundredOneIdArray = Array
    .from(Array(101).keys())
    .map(() => generateUid(5));

function generateUid(length: number) {
  const uidString: string[] = [];
  const uidChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < length; i++) {
    uidString
      .push(uidChars.charAt(Math.floor(Math.random() * uidChars.length)));
  }
  return uidString.join('');
}

for (let i = 0; i < randomOneHundredOneIdArray.length; i++) {
 if(i % idArrayLengthLimit === 0){
     const result = randomOneHundredOneIdArray
       .filter((_,id) => id >= i && id < i + idArrayLengthLimit);
    // Observe result
    console.log(result);
 }
}
0

Here's a more specific case that someone might find valuable. I haven't seen it mentioned here yet.

What if you don't want constant/even chunk sizes, and instead want to specify the indices where the array is split. In that case, you can use this:

const splitArray = (array = [], splits = []) => {
  array = [...array]; // make shallow copy to avoid mutating original
  const chunks = []; // collect chunks
  for (const split of splits.reverse()) chunks.push(array.splice(split)); // go backwards through split indices and lop off end of array
  chunks.push(array); // add last remaining chunk (at beginning of array)
  return chunks.reverse(); // restore chunk order
};

Then:

splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6]) 
// [ [1, 2, 3, 4] , [5, 6] , [7, 8, 9] ]

Note that this will do funny things if you give it non-ascending/duplicate/negative/non-integer/etc split indices. You could add checks for these edge cases (e.g. Array.from(new Set(array)) to de-duplicate.

0

My favorite is the generator generateChunks with the additional function getChunks to execute the generator.

function* generateChunks(array, size) {
    let start = 0;
    while (start < array.length) {
        yield array.slice(start, start + size);
        start += size;
    }
}

function getChunks(array, size) {
    return [...generateChunks(array, size)];
}

console.log(getChunks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9 ] ]

As an addition here the generator generatePartitions with the further function getPartitions to get n arrays of equal size.

function generatePartitions(array, count) {
    return generateChunks(array, Math.ceil(array.length / count));
}

function getPartitions(array, count) {
    return [...generatePartitions(array, count)];
}

console.log(getPartitions([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8, 9 ] ]

An advantage of the generator compared to many other solutions is that not multiple unnecessary arrays are created.

0

In JS,

const splitInChunks = (arr,n) => {
  let chunksArr = [];
  if(arr !=null && arr!= undefined){
      for(i=0; i<arr.length;i+=n){
      if(arr.length-i>=n)
          chunksArr.push(arr.slice(i,i+n))
      else
           chunksArr.push(arr.slice(i,arr.length))
  }
  return chunksArr
  }
}
0

Optimized function with one loop in JS, no slice, reduce or anything

const splitArrayIntoN = (myArray, n) => {
  if (!Number.isSafeInteger(n)) {
    return myArray;
  }
  let count = 0;
  const tempArray = [];
  for (let item = 0; item < myArray.length; item++) {
    if (tempArray[count] && tempArray[count].length !== n) {
      tempArray[count] = [...tempArray[count], myArray[item]];
    }
    if (!tempArray[count]) {
      tempArray[count] = [myArray[item]];
    }
    if (tempArray[count].length === n) {
      count++;
    }
  }
  return tempArray;
};
0

You can combine .filter() and .map() to achieve it.

let array = [];
for (let i = 1; i < 95; i++) array.push(i);
let limit = 10;
console.log(array.filter((item, index) => (index % limit === 0)).map((item, index) => {
    let tmp = [];
    for (let i = limit * index; i < Math.min((index + 1) * limit, array.length); i++) tmp.push(array[i]);
    return tmp;
}));

0

This is what I just came up with. Might be a duplicate but I ain't reading through all these to check.

const toBatches = (src, batchSize) => src.reduce((pv, cv) => {
  const lastBatch = pv.length > 0 ? pv[pv.length - 1] : null;

  !lastBatch || lastBatch.length === batchSize 
    ? pv.push([cv])
    : lastBatch.push(cv); 

  return pv;
}, []);
0

Since this is the first result I came across when trying to "pull" data from an array in chunks, I'll add this here.

When the integrity of the source array is not important, or when trying to "pull" data from the source in chunks, this simplified code can be used:

const chunkedQueue = [1, 2, 3, 4, 5, 6, 7, 8, 9];

while (chunkedQueue.length) {
    const chunk = chunkedQueue.splice(0, 10);

    // Do something with chunk
}

If using a stack approach, rather than a queue, a negative index can be used in the splice function. Though it is important to note, that the order of the items in each chunk is still the same as in the source array:

const chunk = chunkedStack.splice(-10, 10);
0

function groupArr(arr = [], size = 0) {
    if (!Array.isArray(arr) || !arr.length) return [];
    if (arr.length <= size || size <= 0) return [arr];

    const resultArr = [];

    for (let i = 0, j = size, len = arr.length; i < len; j += size) {
        let tempArr = [];

        if (j > len) {
            tempArr = arr.slice(i);
        } else {
            tempArr = arr.slice(i, j);
        }
        i = j;
        resultArr.push(tempArr);
    }

    return resultArr;
}

let arr = [1, 2, 3, 4, 5];
let size = 2;
let result = groupArr(arr, size);

console.log(result);

-2

Well, a nice function for this would be:

function chunk(arr,times){
    if(times===null){var times = 10} //Fallback for users wanting to use the default of ten
   var tempArray = Array() //Array to be populated with chunks
    for(i=0;i<arr.length/times;i++){
     tempArray[i] = Array() //Sub-Arrays        //Repeats for each chunk         
   for(j=0;j<times;j++){
        if(!(arr[i*times+j]===undefined)){tempArray[i][j] = arr[i*times+j]//Populate Sub-  Arrays with chunks
    }
     else{
       j = times //Stop loop
       i = arr.length/times //Stop loop
  }
    }
     }
   return tempArray //Return the populated and chunked array
   }

Usage would be:

chunk(array,sizeOfChunks)

I commented it so you could understand what was going on.

(The formatting is a bit off, I programmed this on mobile)

-2

Neat and clean easy to understand

 let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 let len = nums.length ;

    const chunkArr = (arr, chunkNo) => {
      let newArr = [];
      for(let i = 0; i < len; i++){
        if(nums[0] !== "" && nums[0] !== undefined ){
          let a = nums.splice(0,chunkNo) ; 
          newArr.push(a);
        }
      }
       return newArr ;
    }
    console.log(chunkArr(nums, 5));
1 2
3

Not the answer you're looking for? Browse other questions tagged or ask your own question.