How can I delete an value from an array in jQuery?
var prodCode = ["001","002","003","004","005","006","007","008"];
hopefully i got your question right: you want to delete a single element of an array
var index = $.inArray(value, array);
if (index >= 0) {
array.splice(index, 1);
}
otherwise
$.each(arrayWithValuesToRemove, function (index, element) {
var index = $.inArray(element, array);
if (index < 0) {
return;
}
array.splice(index, 1);
});
if you just want a random removal
var desiredIndex = Math.floor(Math.random() * array.length);
array.splice(desiredIndex, 1);
if you want to keep the index, but not it's value (combine with any of the upper examples):
delete array[index];
if you want to write your own compare-method (eg. object as value):
var compareFunction = function (element) {
// TODO your compare stuff
};
var getIndexFunction = function (array) {
for (var i = 0; i < array.length; i++) {
var element = array[i];
if (compareMethod(element)) {
return i;
}
}
return -1;
};
var index = getIndexFunction(myArray);
if (index >= 0) {
myArray.splice(index, 1);
}
I'm not sure I get your question correctly, but if you want to remove a random element in the middle of the array, you can
array.splice(Math.floor(Math.random() * array.length), 1);
var prodCode = ["001","002","003","004","005","006","007","008"];
var randomElementIndex = Math.floor( Math.random() * prodCode.length );
var removedElement = prodCode.splice(randomElementIndex, 1);
console.log(prodCode); //doesn't have removedElement with the index randomElementIndex anymore
Removes a random element from the array.