Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into chunks

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?

like image 223
Industrial Avatar asked Dec 13 '11 20:12

Industrial


People also ask

What function split an array into chunks?

Example 2: Split Array Using splice() In the above program, the while loop is used with the splice() method to split an array into smaller chunks of an array. In the splice() method, The first argument specifies the index where you want to split an item.

How do you split an array into a smaller array?

Divide and Chunk an Array Into Smaller Arrays JavaScript comes with the Array#splice method. The splice method removes items from an array and returns them as a new array. This way, you can remove the number of items from the source array until it's empty.

How do you split an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

The array.slice method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.

var i,j, temporary, chunk = 10; for (i = 0,j = array.length; i < j; i += chunk) {     temporary = array.slice(i, i + chunk);     // do whatever } 
like image 142
Blazemonger Avatar answered Oct 18 '22 21:10

Blazemonger


Here's a ES6 version using reduce

var perChunk = 2 // items per chunk      var inputArray = ['a','b','c','d','e']  var result = inputArray.reduce((resultArray, item, index) => {    const chunkIndex = Math.floor(index/perChunk)    if(!resultArray[chunkIndex]) {     resultArray[chunkIndex] = [] // start a new chunk   }    resultArray[chunkIndex].push(item)    return resultArray }, [])  console.log(result); // result: [['a','b'], ['c','d'], ['e']]

And you're ready to chain further map/reduce transformations. Your input array is left intact


If you prefer a shorter but less readable version, you can sprinkle some concat into the mix for the same end result:

inputArray.reduce((all,one,i) => {    const ch = Math.floor(i/perChunk);     all[ch] = [].concat((all[ch]||[]),one);     return all }, []) 

You can use remainder operator to put consecutive items into different chunks:

const ch = (i % perChunk);  
like image 32
Andrei R Avatar answered Oct 18 '22 20:10

Andrei R