I need to split a JavaScript array into n
sized chunks.
E.g.: Given this array
["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]
and a n
equals to 4, the output should be this:
[ ["a1", "a2", "a3", "a4"], ["a5", "a6", "a7", "a8"], ["a9", "a10", "a11", "a12"], ["a13"] ]
I aware of pure JavaScript solutions for this problem, but since I am already using Lodash I am wondering if Lodash provides a better solution for this.
I created a jsPerf test to check how much slower the underscore solution is.
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.
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.
chunk() function is used to break the array in to small chunks. Each chunk is an array of size as given.
Take a look at lodash' chunk: https://lodash.com/docs#chunk
const data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]; const chunks = _.chunk(data, 3); console.log(chunks); // [ // ["a1", "a2", "a3"], // ["a4", "a5", "a6"], // ["a7", "a8", "a9"], // ["a10", "a11", "a12"], // ["a13"] // ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
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