Extending JavaScript Arrays - Part 2

Discussion in 'JavaScript and AJAX' started by pradeep, Jul 5, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Continuation of [thread=606]Extending JavaScript Arrays[/thread].

    Some more functions to extend the array manipulation capabilty of JavaScript.

    Code:
    /* Shuffles the Array elements randomly */
     Array.prototype.shuffle=function()
     {
         var i=this.length,j,t;
         while(i--)
         {
             j=Math.floor((i+1)*Math.random());
             t=arr[i];
             arr[i]=arr[j];
             arr[j]=t;
         }
     }
     
     /* Removes redundant elements from the array */
     Array.prototype.unique=function()
     {
         var a=[],i;
         this.sort();
         for(i=0;i<this.length;i++)
         {
             if(this[i]!==this[i+1])
             {
                 a[a.length]=this[i];
             }
         }
         return a;
     }
     
     /* Returns the index of the element matched from the behind */
     Array.prototype.lastIndexOf=function(n)
     {
         var i=this.length;
         while(i--)
         {
             if(this[i]===n)
             {
                 return i;
             }
         }
         return -1;
     }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice