Monthly Archives: February 2013

Code of the Day: Chop up an array into groups using Underscore.js

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;
}

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
Twitter