Last active
December 22, 2015 19:29
-
-
Save Yushell/6520117 to your computer and use it in GitHub Desktop.
Extend JavaScript array to find and remove contained values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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