Shrink an array into a group of smaller arrays using underscore.js
// Make sure to include underscore.js _.mixin({ chunk : function (array, unit) { if (!_.isArray(array)) return array; unit = Math.abs(unit); var results = [], length = Math.ceil(array.length / unit); for (var i = 0; i < length; i++) { results.push(array.slice( i * unit, (i + 1) * unit)); } return results; } }); |
Example:
JSON.stringify( _.chunk([1,2,3,4,5,6,7,8,9], 2) ); // returns "[[1,2],[3,4],[5,6],[7,8],[9]]" |
Here’s the same thing without using Underscore.js
var chunk = function (array, unit) { if (typeof array !== "object") return array; unit = Math.abs(unit); var results = [], length = Math.ceil(array.length / unit); for (var i = 0; i < length; i++) { results.push(array.slice(i * unit, (i + 1) * unit)); } return results; } |
(Page view Count: 115)