5

How can I delete an value from an array in jQuery?

var prodCode = ["001","002","003","004","005","006","007","008"];

3 Answers 3

12

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

if i want to delete a particular index value means, how to do?
2

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);

1 Comment

if i want to delete a particular index value means, how to do?
2
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.

9 Comments

if i want to delete a particular index value means, how to do?
instead of generating the index randomly, you can just provide it to the splice method of the array literal
If you want to get the index of an element from its value, see: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
.indexOf is not supported by every browser. use $.inArray() instead (api.jquery.com/jQuery.inArray)
hence the link to MDN that you obviously didn't check out =) (gives a workaround for non-supporting browsers)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.