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?

3
  • I think this has been answered before stackoverflow.com/questions/1960473/unique-values-in-an-array Commented Sep 15, 2011 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 Commented Sep 15, 2011 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. Commented Sep 15, 2011 at 13:35

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.