Getting distinct array of objects I would like to get a distinct array of objects. The code below is the first thing that came to mind. 

Do you see any room for improvements?



function distinct(objectArray){

    var distinctResult = [];

    $.each(objectArray, function(i, currentObject){
        if(!exists(distinctResult, currentObject))
            distinctResult.push(currentObject);
    });

    return distinctResult;
}

function exists(arr, object){
    var compareToJson = JSON.stringify(object),
        result = false;
    $.each(arr, function(i, existingObject){
        if(JSON.stringify(existingObject) === compareToJson) {
            result = true;
            return false; // break
        }
    });

    return result;
}

var testList = [{ foo: 1 }, { foo: 1 }, { bar: 1 }, { bar: 2, baz: 3 }];

console.log(distinct(testList));
Your code looks OK and will work but I have a few issues with it.

jQuery

You're using $.each in your distinct() function - this is fine, but it means I can now not use your function unless I support jQuery. jQuery is not really known as a general purpose utility library, so if I'm using Angular or Ember, I'm probably not going to want to use your function.

$.each is designed primarily for iterating the DOM rather than general arrays.

Reusability

Your distinct function is not very re-usable. You don't take a function as a parameter for matching, which means I have to rely on your method of determining equality. This might work for your problem space, but it does not for mine - Let us say I want to determine equality between base 64 strings. I cannot use your equality function there, and so if I have an array of base 64 strings I'm buggered.

Comparing JSON strings.

An interesting idea, I will give you that, but this is a bit... weird, and incurs a performance overhead. It certainly threw me off. While there is nothing intrinsically wrong with this approach, it feels dirty.

Behold lodash/uniq!

With all this said and done, there is already a utility function to perform this exact purpose in lodash (arguably the best general-purpose utility library in JavaScript). Granted, it only works on arrays, but so does your example. It also comes with the ability to specify your own matcher, and performs optimizations on sorted arrays.

var testList = [{ foo: 1 }, { foo: 1 }, { bar: 1 }, { bar: 2, baz: 3 }];
console.log(_.uniqBy(testList, function(obj) { return JSON.stringify(obj); });