Tuesday, October 20, 2015

JavaScript: Array Object Extensions

Originally published 

Wed 13 Feb 2013

Editors Notes
There are some fine frameworks these days for JavaScript, but sometimes you want something to work a specific way, and that's fine.  That would be an adequate description of this particular gem.

Original Post
I've culled a few, and written a few, JavaScript Array object extensions to make working with Arrays a bit more complete.  There are plenty of base functions worth understanding, but the following so far requires prototyping out some extended functions.



// extends js base array object using jquery to add a diff function
// arrayA.diff(arrayB)
Array.prototype.diff = function(a) {
    var items = new Array();
 items = $.grep(this,function (item) {
     return jQuery.inArray(item, a) < 0;
 });
 return items;
};
// extends js base array object to add "unique" function
Array.prototype.unique = function( b ) {
 var a = [], i, l = this.length;
 for( i=0; i<l; i++ ) {
  if( a.indexOf( this[i], 0, b ) < 0 ) { if (this[i] !== '') {
   a.push(this[i]);
  } }
 }
 return a;
};
// extends js base array object to add "trim" function - removes empty elements
Array.prototype.trim = function(){
 var a=this;
 var b = [], i, l = this.length;
 for ( i=0; i< l; i++){
  if(a[i]!==''){
   b.push(a[i]);
  }
 }
 return b;
}

Array.prototype.drop = function(f){
 var a = this;
 var b=[], i, l= a.length;
 for (i = 0; i < l; i++) {
  if (a[i]!==f){
   b.push(a[i]);
  }
 }
 return b; 
}

Array.prototype.StringFilter = function(f){
 var a=this;
 var b = [], i, l = this.length;
 for ( i=0; i< l; i++){
  if (a[i].indexOf(f)>0){
   b.push(a[i].split(f).join(''));
  }
  else
  {
   b.push(a[i]);
  }
 }
 return b;
}

No comments:

Post a Comment