Skip to content

Instantly share code, notes, and snippets.

@Yushell
Last active December 22, 2015 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yushell/6520117 to your computer and use it in GitHub Desktop.
Save Yushell/6520117 to your computer and use it in GitHub Desktop.
Extend JavaScript array to find and remove contained values
/*
Usage example:
-- array.contains(1)
Description: Checks if array contains value 1
Demo: http://jsfiddle.net/Yushell/GTSXh/
*/
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
/*
Usage example:
-- array.remove(1)
Description: Removes the second item from the array
-- array.remove(-2)
Description: Removes the second-to-last item from the array
-- array.remove(1,2)
Description: Removes the second and third items from the array
-- array.remove(-2,-1)
Description: Removes the last and second-to-last items from the array
Demo: http://jsfiddle.net/Yushell/6VR5P/
*/
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment