var ar=['apple','mango','ronaldo']
What i want is remove mango so it looks like ['apple','ronaldo']
.
i tried this ar.splice(1,1)
but it gives ['mango']
as output.
var ar=['apple','mango','ronaldo']
What i want is remove mango so it looks like ['apple','ronaldo']
.
i tried this ar.splice(1,1)
but it gives ['mango']
as output.
ar.splice(1,1)
remove element from array
so the array ar
is now ['apple','ronaldo'].
var ar=['apple','mango','ronaldo'];
ar.splice(1,1) // removed 'mango'
ar //['apple','ronaldo'].
Fiddle Demo check console logs
.splice() method remove the specific item into the original array and returns the removed item(s).
Try this:
var ar = ['apple','mango','ronaldo'];
var ind = ar.indexOf('mango');
if (ind > -1) {
ar.splice(ind, 1);
}
console.log(ar);
I recommend to use .splice() method if you want to remove array item using item-index. But you can try this one if want to remove the item by it's value.
var ar= ['apple','mango','ronaldo'];
var removeItem = "mango";
ar = jQuery.grep(ar, function(value) {
return value != removeItem;
});
ar //['apple','ronaldo'].
Problem when you remove the item by value (i.e "mango") : It's remove all the items of array with the name of "mango" See in fiddle
Try this
$(function () {
var ar=['apple','mango','ronaldo']
ar.splice(1,1) // remove first
alert(ar);
});