Skip to content

Instantly share code, notes, and snippets.

@davidlonjon
Created September 11, 2013 06:16
Show Gist options
  • Save davidlonjon/6519907 to your computer and use it in GitHub Desktop.
Save davidlonjon/6519907 to your computer and use it in GitHub Desktop.
JavaScript: Additional Array Prototypes
/**
* Remove value(s) from an array
*
* @return {array} Modified array
*/
if (typeof Array.prototype.remove == 'undefined'
|| typeof Array.prototype.remove == null) {
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
}
/**
* Remove one occurence of value(s) from an array
*
* @return {array} Modified array
*/
if (typeof Array.prototype.removeOneOccurence == 'undefined'
|| typeof Array.prototype.removeOneOccurence == null) {
Array.prototype.removeOneOccurence = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
if ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
}
/**
* Count the number of occurences for a specific value in an array
*
* @param {string} value Value
*
* @return {integer} The number of occurences
*/
if (typeof Array.prototype.countOccurrences == 'undefined'
|| typeof Array.prototype.countOccurrences == null) {
Array.prototype.countOccurrences = function(value) {
var count = 0;
for (var i = 0, j = this.length; i < j; i++) {
if (this[i] == value) {
count++;
}
}
return count;
};
}
/**
* Check if a there is only one value (and its occurences) in an array
*
* @param {string} value Value
*
* @return {boolean} Whether or not the value (and its occurences) is the only one in the array
*/
if (typeof Array.prototype.checkOnly == 'undefined'
|| typeof Array.prototype.checkOnly == null) {
Array.prototype.checkOnly = function(value) {
var occurencesCount = 0;
for (var i = 0, j = this.length; i < j; i++) {
if (this[i] == value) {
occurencesCount++;
}
}
if (occurencesCount == this.length) {
return true;
} else {
return false;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment