4

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?

Dexter
  • 1,128
  • 3
  • 25
  • 51
  • 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 Answers1

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