All web developers require to implement some JavaScript in their web applications.
JavaScript arrays support a few in-built array manipulation methods like push,pop, but we might require more like unshift, shift, sort, shuffle, contains, clear and others.
In JavaScript array being an object, we can extend it.
Below you can find a few examples:
Implementing a simple bubble sort:
Implementing ushift, which inserts an element into the beginning of the array.
Implementing shift, which removes and returns the first element of an array.
Implementing clear, which empties an array.
Implementing contains, which checks where the specified elements exists in the array or not.
Continue to Extending JavaScript Arrays - Part 2
JavaScript arrays support a few in-built array manipulation methods like push,pop, but we might require more like unshift, shift, sort, shuffle, contains, clear and others.
In JavaScript array being an object, we can extend it.
Below you can find a few examples:
Implementing a simple bubble sort:
Code: javascript
Array.prototype.sort=function()
{
var tmp;
for(var i=0;i<this.length;i++)
{
for(var j=0;j<this.length;j++)
{
if(this[i]<this[j])
{
tmp = this[i];
this[i] = this[j];
this[j] = tmp;
}
}
}
};
Code: javascript
Array.prototype.unshift=function(item)
{
this[this.length] = null;/* create a new last element */
for(var i=1;i<this.length;i++)
{
this[i] = this[i-1]; /* shift elements upwards */
}
this[0] = item;
};
Code: javascript
Array.prototype.shift=function()
{
for(var i=1;i<this.length;i++)
{
this[i-1] = this[i] /* shift element downwards */
}
this.length = this.length-1;
};
Code: javascript
Array.prototype.clear=function()
{
this.length = 0;
};
Code: javascript
Array.prototype.contains = function (element)
{
for (var i = 0; i < this.length; i++)
{
if (this[i] == element)
{
return true;
}
}
return false;
};


