Skip to content

Instantly share code, notes, and snippets.

@codylindley
Created May 7, 2010 13:44
Show Gist options
  • Save codylindley/393433 to your computer and use it in GitHub Desktop.
Save codylindley/393433 to your computer and use it in GitHub Desktop.
arrayUtils = {
isString:function(val) {//Returns true if the specified value is a string
return typeof val == 'string';
},
remove:function(arr, obj) {//Removes the first occurrence of a particular value from an array.
var i = this.indexOf(arr, obj);
var rv;
if ((rv = i >= 0)) {
this.removeAt(arr, i);
}
return rv;
},
removeAt:function(arr, i) {//Removes the first occurrence of a particular value from an array.
return Array.prototype.splice.call(arr, i, 1).length == 1;
},
// Returns the index of the first element of an array with a specified
// value, or -1 if the element is not present in the array.
indexOf : Array.prototype.indexOf ?
function(arr, obj, opt_fromIndex) {
return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);
} :
function(arr, obj, opt_fromIndex) {
var fromIndex = opt_fromIndex === null ?
0 : (opt_fromIndex < 0 ?
Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex);
if (this.isString(arr)) {
// Array.prototype.indexOf uses === so only strings should be found.
if (!this.isString(obj) || obj.length != 1) {
return -1;
}
return arr.indexOf(obj, fromIndex);
}
for (var i = fromIndex; i < arr.length; i++) {
if (i in arr && arr[i] === obj){
return i;
}
}
return -1;
}
};
var myArray = ['foo','bar'];
arrayUtils.remove(myArray,'foo');
console.log(myArray);
myArray.push('foo');
console.log(myArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment