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?

2
  • Are the indexes always 0, 1, and 2? Commented Mar 7, 2013 at 11:12
  • yes, always starts from 0 Commented Mar 7, 2013 at 11:14

4 Answers 4

3

Use the splice function :

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

Be careful that this changes the original array.

Sign up to request clarification or add additional context in comments.

6 Comments

No problem, can you bit explain the parameters?
I linked to the complete documentation. But here the first argument is the position and the second one the number of elements to remove.
+1 but would prefer wording the other way around (from index 1, removes 1 element)
@PaulS. Good idea. I edited (you could have to).
@PaulS. I just had a look. 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
|
0

Use splice(). E.g:

abc.splice(1, 1); 

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

Comments

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

Comments

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')+"]"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.