Javascript set(-of-string) functions


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.