I've got an array of objects where each object has fields like title, description, family, etc. How can I perform a jQuery operation that grabs all objects in this array with a unique family name - similar to SQL's DISTINCT clause?
Asked
Active
Viewed 2.4k times
4
-
I think this has been answered before http://stackoverflow.com/questions/1960473/unique-values-in-an-array – Drake Sep 15 '11 at 13:28
-
@Drake - I was hoping to find a jQuery solution if possible, but thank you I did not see that link the in stackoverflow recommendations – Dexter Sep 15 '11 at 13:32
-
@bstakes - nothing that's working obviously. I was using grep to grab elements where I had specific matches but I don't have a specific value I'm grabbing in this case. I also reviewed using data as an option, but again, this requires a value to match against. – Dexter Sep 15 '11 at 13:35
1 Answers
21
You could do:
var array = [{
familyName: "one"},
{
familyName: "two"},
{
familyName: "one"},
{
familyName: "two"}];
var dupes = {};
var singles = [];
$.each(array, function(i, el) {
if (!dupes[el.familyName]) {
dupes[el.familyName] = true;
singles.push(el);
}
});
Singles is an array with only DISTINCT objects
EDIT - i have blogged about this and given a more elaborate answer http://newcodeandroll.blogspot.it/2012/01/how-to-find-duplicates-in-array-in.html

Nicola Peluchetti
- 76,206
- 31
- 145
- 192