Split JavaScript array in chunks using Lodash
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>
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();
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>