Group array values in group of 3 objects in each array using underscore.js
Pure javascript code:
function groupArr(data, n) {
var group = [];
for (var i = 0, j = 0; i < data.length; i++) {
if (i >= n && i % n === 0)
j++;
group[j] = group[j] || [];
group[j].push(data[i])
}
return group;
}
groupArr([1,2,3,4,5,6,7,8,9,10,11,12], 3);
Here's a short and simple solution abusing the fact that .push
always returns 1
(and 1 == true
):
const arr = [0, 1, 2, 3, 4, 5, 6]
const n = 3
arr.reduce((r, e, i) =>
(i % n ? r[r.length - 1].push(e) : r.push([e])) && r
, []); // => [[0, 1, 2], [3, 4, 5], [6]]
Plus, this one requires no libraries, in case someone is looking for a one-liner pure-JS solution.