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:
TwitterLinkedInYouTube

Code of the day: Get unique objects from an array of json objects.

Inspired from Removing duplicate objects with Underscore for Javascript

Source:

/**
@function _.uniqObjects
@require Underscore.js and json.stringify
@purpose return an array of objects without duplicated objects.
*/
_.uniqObjects = function( arr ){
	return _.uniq( _.collect( arr, function( x ){
		return JSON.stringify( x );
	}));
};

Example:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
_.uniqObject( foo );  // returns [ { "a" : "1" }, { "b" : "2" } ]

Larry Battle

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

More Posts - Website

Follow Me:
TwitterLinkedInYouTube