Skip to content

Instantly share code, notes, and snippets.

@UziTech
Last active October 17, 2015 03:38
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 UziTech/742972feee34a3c63188 to your computer and use it in GitHub Desktop.
Save UziTech/742972feee34a3c63188 to your computer and use it in GitHub Desktop.
Remove items from an array. Optionally limit the number of items to remove from the beginning or end of the array.
/**
* Author: Tony Brix
* Website: tony.brix.ninja
* License: MIT
* Description: Remove items from an array. Optionally limit the number of items to remove from the beginning or end of the array.
* Examples:
* var a = [1, 2, 3, 1, 2, 3];
* a.remove(1); // [2, 3, 2, 3]
* a.remove(2, 1); // [1, 3, 1, 2, 3]
* a.remove(3, -1); // [1, 2, 3, 1, 2]
* a.remove(function(el){ return el > 2; }); // [1, 2, 1, 2]
* a.remove(function(el, i){ return i % 2; }); // [1, 3, 2]
*/
Array.prototype.remove = function (predicate, limit, thisArg) {
var func, numElements, length;
//get function that returns true for elements to remove
if (typeof predicate === "function") {
func = predicate;
} else {
func = function (el) {
return el === predicate;
};
}
//get number of elements to remove
if (typeof limit === "number") {
numElements = limit;
} else {
numElements = false;
}
//get length of this
length = this.length;
//get new array
var newArray = [];
if (numElements < 0) {
//start from last element
var numRemoved = 0;
for (var i = length - 1; i >= 0; i--) {
if ((numElements !== false && numRemoved === -numElements) || !func.call(thisArg, this[i], i, this)) {
newArray.unshift(this[i]);
} else {
numRemoved++;
}
}
} else {
//start from first element
var numRemoved = 0;
for (var i = 0; i < length; i++) {
if ((numElements !== false && numRemoved === numElements) || !func.call(thisArg, this[i], i, this)) {
newArray.push(this[i]);
} else {
numRemoved++;
}
}
}
return newArray;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment