Advertisement
Booster

Array Extensions JS

Apr 4th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*Removes the first element found from left to right in the array
  2. Second argument should be truthy to remove all elements*/
  3. Array.prototype.remove = function(arg, all){
  4.     for(var i = 0; i < this.length; i++){
  5.         if(this[i] === arg){
  6.             this.splice(i,1);
  7.  
  8.             if(!all)
  9.                 break;
  10.             else
  11.                 i--;
  12.         }
  13.     }
  14. };
  15.  
  16. //Removes the element at the position
  17. Array.prototype.removeAt = function(position){
  18.     this.splice(position,1);
  19. };
  20.  
  21. //Removes all elements of the array
  22. Array.prototype.clear = function(){
  23.     this.length = 0;
  24. };
  25.  
  26. //inserts an element at a given position
  27. Array.prototype.insertAt = function(arg, position){
  28.     this.splice(position, 0, arg);
  29. };
  30.  
  31. //Checks if the array contains the given element
  32. Array.prototype.contains = function(arg){
  33.     for(var i = 0; i < this.length; i++)
  34.         if(this[i] === arg)
  35.             return true;
  36.     return false;
  37. };
  38.  
  39. //Counts the occurrences of a given element in array
  40. Array.prototype.occurs = function(arg){
  41.     var counter = 0;
  42.  
  43.     for(var i = 0; i< this.length; i++){
  44.         if(this[i] === arg)
  45.             counter++;
  46.     }
  47.  
  48.     return counter;
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement