Hereby my first blogpost ever. This post will introduce some handy extensions to the javascript array object. The background for this post is the javascript array objects lack of some very basic functionality.
For a full reference of the javascript array objects methods follow this link to w3schools
.remove()
The javascript array remove method is simply used to remove an element from the array. Existing ways of performing this task leaves a hole in the array wich then has to be handled. I prototype the javascript array object, so the remove method can be called directly on an array.
Array.prototype.remove = function(index) {
var rtrnArr = [];
for (var i = 0; i < this.length; i++) {
if (i !== index) {
rtrnArr[rtrnArr.length] = this[i];
}
}
return rtrnArr;
};
jQuery(function() {
var test = ["1", "2", "a", "4", "1", "b", "3", "c", "11", "483"],
testTxt = "";
testTxt = "<br />Array with strings: " + test;
testTxt += "<br /><br />Fjerner index 3: " + test.remove(3);
jQuery("div#RemoveTest").html(testTxt);
});
The results:
.sortArray()
The javascript array object allready have a sort method. The native method sort only alphabetically though, unless you pass a function to do the job. The sortArray method gives us two new functionalities.
- It sorts both alphabetically and numerically depending on the content of the array.
- It sorts ascending by default, but you can pass “desc” as a parameter to sort descending.
Array.prototype.sortArray = function(sortAttr) {
if (this[0]) {
sortAttr = sortAttr ? sortAttr : "asc";
if (typeof this[0] === "string") {
this.sort();
if (sortAttr.toLowerCase() === "desc") {
this.reverse();
}
} else {
this.sort(function(a, b) {
return sortAttr.toLowerCase() === "desc" ? b - a : a - b;
});
}
}
return this;
};
jQuery(function() {
var test = ["1", "2", "a", "4", "1", "b", "3", "c", "11", "483"],
testNumbers = [1, 2, 3, 4, 1, 2, 3, 4],
testTxt = "";
testTxt = "String array: " + test;
testTxt += "<br />Array with numbers: " + testNumbers;
testTxt += "<br /><br />Ordered String array asc: " + test.sortArray();
testTxt += "<br />Ordered String array desc: " + test.sortArray("desc");
testTxt += "<br /><br />Ordered number array asc: " + testNumbers.sortArray();
testTxt += "<br />Ordered number array desc: " + testNumbers.sortArray("desc");
jQuery("div#SortTest").html(testTxt);
});
The result:
This post was written in
Array,
Extension,
Javascript. Ad
permalink to favorites. Follow all comments with
RSS feed for this posts.
or a trackback:
Trackback URL.
|
dansk version