Posted By

scarfboy on 07/17/08


Tagged

javascript lists sets


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

wirenaught


Javascript set(-of-string) functions


 / Published in: JavaScript
 

Exploits hash keys uniqueness, but in doing so effectively toString()s everything, meaning this should not be used for much beyond strings and perhaps integers.

I used this when I wanted to do some client-side filtering of (integer) identifiers.

  1. function unique(l) {
  2. var o=new Object(),ret=[];
  3. for(i in l){o[l[i]]=1}
  4. for(k in o){ret.push(k)}
  5. return ret;
  6. }
  7.  
  8. function union(l1,l2) {
  9. var o=new Object(),ret=[];
  10. for(i in l1){o[l1[i]]=1}
  11. for(i in l2){o[l2[i]]=1}
  12. for(k in o){ret.push(k)}
  13. return ret;
  14. }
  15.  
  16. function intersect(l1,l2) {
  17. var o=new Object(), ret=[];
  18. for (i in l1) o[l1[i]]=1; //this value is ignored
  19. for (i in l2)
  20. if (o[l2[i]]!==undefined)
  21. ret.push(l2[i]);
  22. return ret;
  23. }
  24.  
  25. function except(l1,l2) {
  26. var o=new Object(), ret=[];
  27. for (i in l1) o[l1[i]]=1;
  28. for (i in l2) delete(o[l2[i]]);
  29. for (i in o) ret.push(i);
  30. return ret;
  31. }

Report this snippet  

You need to login to post a comment.