Skip to content

Instantly share code, notes, and snippets.

@jawinn
Created March 1, 2014 23:44
Show Gist options
  • Select an option

  • Save jawinn/9299470 to your computer and use it in GitHub Desktop.

Select an option

Save jawinn/9299470 to your computer and use it in GitHub Desktop.
Array Helpers for JavaScript + jQuery
// For getting unique values in array
// usage:
// var duplicates = [1,3,4,2,1,2,3,8];
// var uniques = duplicates.unique(); // result = [1,3,4,2,8]
Array.prototype.contains = function(v) {
for(var i = 0; i < this.length; i++) {
if(this[i] === v) return true;
}
return false;
};
Array.prototype.unique = function() {
var arr = [];
for(var i = 0; i < this.length; i++) {
if(!arr.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
// SORT ARRAY BY NUMBER, NOT ALPHABETICAL
// Usage: myArr = myArr.sortNumber();
Array.prototype.sortNumber = function(){
return this.sort(function(a,b){return b - a});
}
// REMOVE ITEM FROM ARRAY BY VALUE
// This can be a global function or a method of a custom object, if you aren't allowed to
// add to native prototypes. It removes all of the items from the array that match any of the arguments.
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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment