Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicate objects with Underscore for Javascript

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?

like image 934
plus- Avatar asked Mar 29 '12 10:03

plus-


1 Answers

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

  1. Callback return value used for comparison
  2. First comparison object with unique return value used as unique
  3. underscorejs.org demonstrates no callback usage
  4. lodash.com shows usage

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

like image 175
Shanimal Avatar answered Oct 05 '22 11:10

Shanimal