Based on all the answers which were mainly correct and taking into account the best practices suggested (especially not using Array.prototype directly), I came up with the below code. Let me know if there is anything you find wierd. But should be fine:
// Extending the core Array Object
MyArray.prototype = new Array();
MyArray.prototype.constructor= MyArray;
/**
* New array class constructor
*/
function MyArray() {
// Constructor code here
}
/**
* Excludes a value from array and returns the rest of array
* @param {string/number/boolean} excludedValue Value which should be removed
* @return {array}
*/
MyArray.prototype.without = function(excludedValue) {
var valueType = typeof excludedValue;
if (this.length < 1)
return [];
if (valueType == 'object' || valueType == 'array' || valueType == 'undefined')
throw "Argument can not be object, array or undefined";
for (var index in this) {
if (this[index] === excludedValue) {
this.splice(index, 1);
index--;
}
};
return this;
};
// How to use
var arr = new MyArray();
arr = [1,2,3,4,5,"name", false];
arr.without(1); // will change the array to [2,3,4,5,"name", false]
arr.without("name"); // will change the array to [2,3,4,5, false]
arr.without(false); // will change the array to [2,3,4,5]
arr.without([1,2]); // will throw error as argument can not be array
arr.without({bar: "foo"}); // will throw error as argument can not be object
After two years of coding I now have a more preferred solution as below:
function arrayWithout(arr, values) {
var isArray = function(canBeArray) {
if (Array.isArray) {
return Array.isArray(canBeArray);
}
return Object.prototype.toString.call(canBeArray) === '[object Array]';
};
var excludedValues = (isArray(values)) ? values : [].slice.call(arguments, 1);
for (var i = arr.length - 1; i >= 0; i--) {
if (excludedValues.indexOf(arr[i]) > -1) {
arr.splice(i, 1);
}
}
return arr;
}
indexOf
in IE. – Scotty.NET Sep 13 '13 at 7:48delete
should be more performant in the short term, because it won't have to shift the later items.forEach
,map
andfilter
will automatically skip processing for undefined (deleted) items. But it's probably not ideal if you will be adding a lot of things to your array in future, or reading it many times. – joeytwiddle Jul 29 '16 at 8:55