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?
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.
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.
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.
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 }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With