How to delete or delete an array value randomly in jQuery?

How can I remove a value from an array in jQuery?

var prodCode = ["001","002","003","004","005","006","007","008"];
+5
source share
3 answers

I hope that I understand your question correctly: do you want to delete one element of the 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 random deletion

var desiredIndex = Math.floor(Math.random() * array.length);
array.splice(desiredIndex, 1);

if you want to keep the index, but not its value (in combination with any of the above examples):

delete array[index];

if you want to write your own comparison method (for example, an object as a 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);
}
+12
source

I'm not sure I'm asking 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);
+2
source
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

random .

+2

All Articles