How to add/remove an element to/from javascript array at/from the given position?

In previous week we have a requirement to add an element to javascript array at the given position.

To fulfill our requirement we have used javascript splice method.

The splice() method is changing the original array and add/remove an element to/from the given position.

It is returning the removed element. And it has three arguments.

Where first argument is “index”, which is an integer to specify at which position add/remove element.

Second argument is “how many”, which is the number of elements to be removed. If this argument is set to 0 then no element will be removed.

And third argument is “element”, which is the new element(s) will be added to the array and this argument is optional.

Now follow the under given example, which adds/removes an element to/from javascript array at/from the given position.

var vehicles = ["bicycle", "car", "bus"];
vehicles.splice(2,0,"truck");
document.write("Added: " +  vehicles + "<br />");
document.write("Removed: " + vehicles.splice(1,2,"tractor,train") + "<br />");
document.write("Vehicles: " + vehicles);
Advertisements

Speak Your Mind

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: