Categories: Frontend Tech

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.

View Comments

  • Great article but i get an error when I try to implement it. I'm creating a javascript object from my SharePoint list and trying to apply the _.uniqObject but it's not being recognized. The error says "Object doesn't support this property or method" Here's my code: Any ideas? Thanks for any help you can provide.

    function buildProjExecution(chartType) {

    getProjects();

    arrProjs = _.uniqObject(arrProjs); //<-- Here's where I get the error

    $.each(ProjectDataArray, function (index, value) {

    alert(index + ':' + value);

    });

    alert("Prog Num: "+arrProjs.length); //<-- 20 values here also after the uniq()

    }

    //Get values into an array so I can use the _.uniq() to remove the duplicates so I can add funding amount

    function getProjects() {

    var i=0;

    $().SPServices({

    operation: "GetListItems",

    listName: "Project",

    async: false,

    CAMLViewFields: "",

    CAMLRowLimit: 20,

    CAMLQuery: ""+beginFY+""+endFY+"",

    completefunc: function (xData, Status) {

    $(xData.responseXML).SPFilterNode("z:row").each(function () {

    ProjectItem = new Object();

    ProjectItem.projNumber = $(this).attr("ows_ProjNumber");

    ProjectItem.amtProjected = $(this).attr("ows_AmtProjected");

    ProjectDataArray[i] = ProjectItem;

    i++;

    });

    }

    });

    }

    /*

    @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 );

    }));

    };

    • You have to extend underscore so that it recognizes this custom method as an underscore method:

      _.mixin({
      myCustomFunction: function() {
      console.log("My custom function!");
      }
      });

  • Doesn't this function return a JSON string as opposed to an object?

    Here's how I implemented it:

    uniqObjects: function( arrayOfObj ){
    return _.chain(arrayOfObj)
    .map(function(obj) {
    return JSON.stringify(obj)
    })
    .uniq()
    .map(function(stringified) {
    return JSON.parse(stringified)
    })
    .value();
    }

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago