Working with javascript arrays today, I found some handy functions:
- Creating an array :
var ray = [];
- Joining two arrays :
var resultArray = ArrayOne.concat(ArrayTwo);
- Getting only unique items in an array :
(Jquery has a unique function, but it does not work on strings / numbers)
Array.prototype.unique = function() {
var result = new Array();
o: for (var i = 0, n = this.length; i < n; i++) {
for (var x = 0, y = result.length; x < y; x++) {
if (result[x] == this[i]) {
continue o;
}
}
result[result.length] = this[i];
}
return r;
}
- For each in JavaScript(using JQuery):
(although JavaScript has for (item in collection) functionality, it is not useful as it also iterates through the methods of the object.)
$.each(collection, function(index, value) { alert(index + ' : ' + value); });
- Bonus JavaScript : Splitting a string by multiple delimiters :
use a regular expression :
var result = myString.split(/[DELIMITERS]+/);
just replace DELIMITERS with the delimiters you want (one character delimiters)