0

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.

user3508453
  • 808
  • 3
  • 13
  • 24
  • possible duplicate of [How to remove specifc value from array using jQuery](http://stackoverflow.com/questions/3596089/how-to-remove-specifc-value-from-array-using-jquery) – Aashish P Jun 11 '14 at 10:21
  • 1
    Works fine - [see here](http://jsfiddle.net/TUDsG/). Sounds like you're assigning the return value of `splice()`, rather than just splicing the array – billyonecan Jun 11 '14 at 10:22
  • Oh got the error thanks billy – user3508453 Jun 11 '14 at 10:26

3 Answers3

1

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

Tushar Gupta - curioustushar
  • 54,013
  • 22
  • 95
  • 103
1

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

Working Example

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'].

Working Example

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

Ishan Jain
  • 7,501
  • 9
  • 45
  • 72
0

Try this

$(function () {
   var ar=['apple','mango','ronaldo']
   ar.splice(1,1) // remove first
   alert(ar);
});

DEMO

Sridhar R
  • 19,414
  • 6
  • 36
  • 35