Removing duplicate objects with Underscore for Javascript

javascript, json, underscore.js

Solution

.uniq/.unique accepts a callback

var list = [{a:1,b:5},{a:1,c:5},{a:2},{a:3},{a:4},{a:3},{a:2}];

var uniqueList = _.uniq(list, function(item, key, a) { 
    return item.a;
});

// uniqueList = [Object {a=1, b=5}, Object {a=2}, Object {a=3}, Object {a=4}]

Notes:

- Callback return value used for comparison

- First comparison object with unique return value used as unique

- underscorejs.org demonstrates no callback usage

- lodash.com shows usage

Another example : using the callback to extract car makes, colors from a list

Problem

I have this kind of array: ``` var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ]; ``` I'd like to filter it to have: ``` var bar = [ { "a" : "1" }, { "b" : "2" }]; ``` I tried using _.uniq, but I guess because `{ "a" : "1" }` is not equal to itself, it doesn't work. Is there any way to provide underscore uniq with an overriden equals function?

Original source