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" } ]

(Page view Count: 441)