By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,715 Members | 1,256 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,715 IT Pros & Developers. It's quick & easy.

Remove duplicate object values in array

P: 1
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?
Nov 13 '06 #1
Share this Question
Share on Google+
1 Reply


gits
Expert Mod 5K+
P: 5,390
hi ...

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

Expand|Select|Wrap|Line Numbers
  1. var sDat = [
  2.     { sid:12, scode:"code", sname:"Sam" },
  3.     { sid:12, scode:"code", sname:"Sam" },
  4.     { sid:139, scode:"code", sname:"Jake"}
  5. ];
  6.  
  7. function cleanup(arr, prop) {
  8.     var new_arr = [];
  9.     var lookup  = {};
  10.  
  11.     for (var i in arr) {
  12.         lookup[arr[i][prop]] = arr[i];
  13.     }
  14.  
  15.     for (i in lookup) {
  16.         new_arr.push(lookup[i]);
  17.     }
  18.  
  19.     return new_arr;
  20. }
  21.  
  22. var n = cleanup(sDat, 'sid');
  23.  
that makes use of javascript objects and the for-in loop construct ...

kind regards
Apr 8 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.