Posted By

kouphax on 10/17/08


Tagged

javascript pushIf


Versions (?)

Array Push If


 / Published in: JavaScript
 

pushIf(array[, function]) --> array

Array.pushIf accepts an array and an optional selector function. If the selector function is supplied the current item in the passed array will be pushed onto the current array if it returns true otherwise it is ignored. If no seletor is supplied items will only be pushed if they are not members of the array already.

The selector function is passed the current item and it's current scope is the target array.

Optional non-prototype extending solution is included.

  1. /**
  2.  * Push all items in passed array into current array if the
  3.  * function returns true. If no function passed in then only
  4.  * pushes items if the are not currently in array
  5.  */
  6. Array.prototype.pushIf = function(i,f){
  7. var func = f || function(it){return this.indexOf(it) == -1}
  8. for(var x=0; x<i.length; x++){
  9. if(func.call(this,i[x])){
  10. this.push(i[x])
  11. }
  12. }
  13. return this;
  14. }
  15.  
  16. /** non prototype extending method ---------------------------- */
  17.  
  18. Array.pushIf = function(t,i,f){
  19. var func = f || function(it){return this.indexOf(it) == -1}
  20. for(var x=0; x<i.length; x++){
  21. if(func.call(t,i[x])){
  22. t.push(i[x])
  23. }
  24. }
  25. return t;
  26. }

Report this snippet  

You need to login to post a comment.