Split JavaScript array in chunks using Lodash

lodash chunk
lodash split array into two
javascript chunk array
lodash split array into n groups
lodash npm
javascript split large array
js group array into chunks
lodash chunk object

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.

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>

Split JavaScript array in chunks using Lodash, If array can't be split evenly, the final chunk will be the remaining elements. Creates an array of array values not included in the other given arrays using Despite multiple requests, the core-js maintainer has made it clear: any attempt to fix  Split JavaScript array in chunks using Lodash-ThrowExceptions. Published by bear on April 10, 2020. Exception or error: I need to split a JavaScript array into n

For Underscore based solution try this:

var data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"];
var n = 3;
var lists = _.groupBy(data, function(element, index){
  return Math.floor(index/n);
});
lists = _.toArray(lists); //Added this to convert the returned object to an array.
console.log(lists);

Using the chain wrapper method you can combine the two statements as below:

var data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"];
var n = 3;
var lists = _.chain(data).groupBy(function(element, index){
  return Math.floor(index/n);
}).toArray()
.value();

Array, If you are new to javaScript and lodash this might not be a good starting point for you, as I assume that you have at least got you feet wet with  possible duplicate of Split javascript array in chunks using underscore.js – Bergi Oct 4 '13 at 12:30 I think this is a pure JS task , any use of lodash methods will make it considerably slower. If you want to use it within the library, .mixin() the pure implementation.

A possibly simpler expression:

const coll = [ "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9" ];
const n = 2;
const chunks = _.range(coll.length / n).map(i => coll.slice(i * n, (i + 1) * n));
console.log(chunks);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Example of the _.chunk array method in lodash, You an use .slice() to accomplish this. I don't understand this point and have no clue how to code it. This is my code: chunk (array, size = 1){ let arrayChunks  Creates an array of elements split into groups the length of size. If array can’t be split evenly, the final chunk will be the remaining elements. Since. 3.0.0. Arguments. array (Array): The array to process. [size=1] (number): The length of each chunk; Returns (Array): Returns the new array of chunks. Example

Underscore supports _.chunk() natively as of version 1.9.0.

const data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"];
const chunks = _.chunk(data, 4);
console.log(chunks);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>

Re-create Lodash Library - chunk() method, Foldr is not as useful in JavaScript as it would be in a language with lazy evaluation. Split list into two arrays: one whose elements all satisfy predicate and one Chunks an array into multiple arrays, each containing length or fewer items. So if there is an original array of 20 e-mails I will need to split them up into 2 arrays of 10 each. or if there are 15 e-mails in the original array, then 1 array of 10, and another array of 5.

try this one it is much more practical (for example, if you would want to split the array based on amount of items to be container in each sub array):

function chunk(arr, start, amount){
    var result = [], 
        i, 
        start = start || 0, 
        amount = amount || 500, 
        len = arr.length;

    do {
        //console.log('appending ', start, '-', start + amount, 'of ', len, '.');
        result.push(arr.slice(start, start+amount));
        start += amount;

    } while (start< len);

    return result;
};

and the use in your case:

var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],
    chunked = chunk(arr, 0, Math.floor(arr.length/3)); //to get 4 nested arrays

console.log(chunked);

and another case:

var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],
    chunked = chunk(arr, 0, 3); // to get 6 nested arrays each containing maximum of 3 items

console.log(chunked);

Underscore.js, With native JavaScript arrays, you can slice off the first portion of an array using the A large collection is created and it's split into chunks of smaller collections. Definition and Usage. The split() method is used to split a string into an array of substrings, and returns the new array. Tip: If an empty string ("") is used as the separator, the string is split between each character. Note: The split() method does not change the original string.

Slicing collections into smaller pieces, Just to be clear: you should probably use Lodash – just make sure you import the If array can't be split evenly, the final chunk will be the remaining elements. plain js. const chunk = (arr, chunkSize = 1, cache = []) => { const tmp = [arr] if  Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements. Since. 3.0.0 Arguments. array (Array): The array to process. [size=1] (number): The length of each chunk. Returns (Array): Returns the new array of chunks. Example _.

You Might Not Need Lodash, Using a for loop and the slice function. Basically, every method will use the slice method in order to split the array, in this case what makes this  Install n_ for Lodash use in the Node.js < 6 REPL. Why Lodash? Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. Lodash’s modular methods are great for:

How to split an array into chunks of the same size easily in Javascript, slice.js' /** * Creates an array of elements split into groups the length of last chunk with this value * @returns {Array} Returns the new array of  It breaks a single dimensional array into a multidimensional array and that is more or less the basic idea of the chunk method. 3 - Matrix use example of _.chunk, and _.chunks friend _.zip. One example that comes to mind is a situation in which you have some pixel data stored in a linear array, and I want it organized in a 2d matrix.

Comments
  • It would be helpful if lodash and underscore both backwards compatible APIs
  • @Jonah That's true. The previous answer is not longer the best one, therefore I updated the accepted answer for the sake of the readers :)
  • Weirdly, Underscore's groupBy returns an object, not an array. Not a dealbreaker--you get basically the same functionality--but an odd bit of semantics. Edit: Oh, it does that to maintain chainability. Still interesting.
  • @Cesar Canassa: For the sake of future developers who read that code, please consider putting that as a function in a custom library if you will use it a lot, or commenting it well if you won't :)
  • @Jordan: Didn't realize that. Edited the answer to conver the object to array.
  • While I'm all for using Underscore for the things it does best (and the OP asked for an Underscore-based solution so the isn't undeserved) and for functional solutions, it seems like this solution introduces a ton of overhead. As @ajax33321 points out, splice in a loop is still a three-liner and, I'm guessing, way more performant. If your arrays are short, it probably doesn't matter, but if you're dealing with hundreds or thousands of items, do keep an eye on its performance.
  • This is no longer the best solution. Please use chunk() instead
  • Simpler than what? Answers should stand alone.
  • That start parameter is not really practical imho. You usually would not want to pass it; but you always need to specify the chunk size. Better swap those two parameters.
  • Why is this a do while loop? No one wants to get empty chunks.