Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

three handy Array functions: pull(), insert(), replace() 2

Status
Not open for further replies.

jemminger

Programmer
Jun 25, 2001
3,453
US
i don't think equivalent functions exist in core js, so i created these for convenience:


Code:
Array.prototype.pull = function (arg) {
	//  pulls an element out of an array, returns the single element.
	//  array.length becomes one less.
	//  may pass the index or value of element to remove
	var oEl, tmp;

	if (typeof arg == "number") {
		oEl = this[arg];
		tmp = this.slice(0,arg).concat(this.slice(arg + 1));
	}
	else if (typeof arg == "string") {
		for (var x = 0; x < this.length; x++) {
			if (this[x] == arg) {
				oEl = this[x];
				tmp = this.slice(0,x).concat(this.slice(x + 1));
				break;
			}
		}
	}
	if (typeof oEl != &quot;undefined&quot;) {
		this.length = 0;
		for (var x = 0; x < tmp.length; x++) 
			this[x] = tmp[x];
		return oEl;
	}
	else return null;
}

Array.prototype.replace = function (id, val) {
	//  replaces the element in Array at index &quot;id&quot; with value &quot;val&quot;
	var tmp = this.slice(0,id).concat(val, this.slice(id+1));
	this.length = 0;
	for (var x = 0; x < tmp.length; x++) {
		this[x] = tmp[x];
	}
	return this;
}

Array.prototype.insert = function (id, val) {
	//  inserts value &quot;val&quot; into Array at index &quot;id&quot;
	//  Array.length increases by one
	tmp = this.slice(0,id).concat(val,this.slice(id));
	this.length = 0;
	for (var x = 0; x < tmp.length; x++) {
		this[x] = tmp[x];
	}
	return this;
}

use them like so:
[tt]
var array1 = [0,1,2,3,4];
alert(&quot;pull(2) returns: &quot; + array1.pull(2));
alert(&quot;array1 now == [&quot; + array1 + &quot;]&quot;);
alert(&quot;insert(2,2) returns: &quot; + array1.insert(2,2));
alert(&quot;replace(2, \&quot;two\&quot;) returns: &quot; + array1.replace(2, &quot;two&quot;));
[/tt]
=========================================================
while (!succeed) try();
-jeff
 
hey those are real handy, thanks jemminger
 
oops, forgot the star.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top