Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Finding Distinct Values in Object Array

Tags:

jquery

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?

like image 440
Dexter Avatar asked Dec 01 '22 01:12

Dexter


1 Answers

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

like image 146
Nicola Peluchetti Avatar answered Jan 01 '23 09:01

Nicola Peluchetti