Remove duplicate object values in array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JTreefrog
    New Member
    • Nov 2006
    • 1

    Remove duplicate object values in array

    Hello - I've read a ton of stuff about deleting duplicate values in an array. They are all very useful - they just haven't addressed an array of objects.

    Here's my array:
    [HTML]
    var sDat = [{
    sid:12,
    scode:"code",
    sname:"Sam"
    },
    {
    sid:12,
    scode:"code",
    sname:"Sam"
    },
    {
    sid:139,
    scode:"code",
    sname:"Jake"
    }];
    [/HTML]
    The array is produced from JSON sent to me from a database query. I can't do a "group by" in the sql query - i actually need the repeats in a different array.

    Anyway - I want to be able to remove duplicate sDat.sid entries in my sDat array - but I'm having difficulties discovering a way to handle it.

    Any ideas?
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    hi ...

    for such tasks we may use something like the following example:

    [CODE=javascript]var sDat = [
    { sid:12, scode:"code", sname:"Sam" },
    { sid:12, scode:"code", sname:"Sam" },
    { sid:139, scode:"code", sname:"Jake"}
    ];

    function cleanup(arr, prop) {
    var new_arr = [];
    var lookup = {};

    for (var i in arr) {
    lookup[arr[i][prop]] = arr[i];
    }

    for (i in lookup) {
    new_arr.push(lo okup[i]);
    }

    return new_arr;
    }

    var n = cleanup(sDat, 'sid');
    [/CODE]
    that makes use of javascript objects and the for-in loop construct ...

    kind regards

    Comment

    Working...