0

I have an array like:

var abc = ["a","b","c"];

And the indexes are 0,1,2

Suppose, I want to delete the 2nd item "b" and I the indexes swipe!

Out put:

abc = ["a","c"]

and the indexes are 0,1

How can I achieve this?

Shahid Karimi
  • 4,096
  • 17
  • 62
  • 104

4 Answers4

3

Use the splice function :

abc.splice(1,1) // from index 1, removes 1 element

Be careful that this changes the original array.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • No problem, can you bit explain the parameters? – Shahid Karimi Mar 07 '13 at 11:17
  • I linked to the complete documentation. But here the first argument is the position and the second one the number of elements to remove. – Denys Séguret Mar 07 '13 at 11:17
  • 1
    +1 but would prefer wording the other way around (`from index 1, removes 1 element`) – Paul S. Mar 07 '13 at 11:21
  • @PaulS. Good idea. I edited (you could have to). – Denys Séguret Mar 07 '13 at 11:24
  • @dystroy Yes, but I would feel `This edit is too minor; [...] edits should be substantive improvements addressing multiple issues in the post.` If you want to offer a way to do the same without modifying the original array, you could also add `var ac = abc.slice().splice(1, 1);` after your warning. (This time I'd feel the change too radical) – Paul S. Mar 07 '13 at 11:32
  • 1
    @PaulS. I just [had a look](http://stackoverflow.com/users/1615483/paul-s?tab=activity). I'm not surprised to see you don't edit too much I see. But in this precise case I don't feel the need for the cloning addition, as *"I like concise, easy-to-read questions and answers"* :p – Denys Séguret Mar 07 '13 at 11:40
0

Use splice(). E.g:

abc.splice(1, 1);

would perform what you wanted in your example. abc[1] would now be "c".

Matt Cain
  • 5,638
  • 3
  • 36
  • 45
0

You can use the array splice abc.splice(1,1);

Details: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice

karthick
  • 11,998
  • 6
  • 56
  • 88
0

Have a look on it... I think this is what you want...

var arr = ["a","b","c"];

arr.splice(1,1);

alert("["+arr.indexOf('a')+","+arr.indexOf('c')+"]");
Paul S.
  • 64,864
  • 9
  • 122
  • 138
Aman Gupta
  • 5,548
  • 10
  • 52
  • 88