Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split JavaScript array in chunks using Lodash

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.

Edit:

I created a jsPerf test to check how much slower the underscore solution is.

like image 791
Cesar Canassa Avatar asked Dec 19 '11 19:12

Cesar Canassa


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 in JavaScript?

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.

What does Lodash chunk do?

chunk() function is used to break the array in to small chunks. Each chunk is an array of size as given.


1 Answers

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>
like image 168
Edo Avatar answered Oct 05 '22 01:10

Edo