Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JSON array unique [duplicate]

Possible Duplicate:
Array unique values
Get unique results from JSON array using jQuery

Im having a JSON string like this

[
 Object { id="38",product="foo"},
 Object { id="38",product="foo"},
 Object { id="38",product="foo"},
 Object { id="39",product="bar"},
 Object { id="40",product="hello"},
 Object { id="40",product="hello"}

]

There are duplicate values in this JSON array..how can i make this JSON array unique like this

[
 Object { id="38",product="foo"},
 Object { id="39",product="bar"},
 Object { id="40",product="hello"}
]

.Im looking for a suggestion that uses less iterations, Jquery $.inArray is not working in this case.

Suggestion to use any third party libraries are welcome.

like image 945
coolguy Avatar asked Dec 16 '22 20:12

coolguy


1 Answers

You can use underscore's uniq.

In your case, you need to provide an iterator to extract 'id':

array = _.uniq(array, true /* array already sorted */, function(item) {
  return item.id;
});
like image 99
Laurent Perrin Avatar answered Dec 26 '22 18:12

Laurent Perrin