Array III - removing, inserting and extracting element

It is possible to add or remove elements in array. Follow the example below for more info:

shift() - To remove first element
var cities = ["London", "Reading", "Liverpool", "Manchester", "Basingstoke"];
cities.shift();
alert(cities);

unshift() - To add element to the first
var cities = ["London", "Reading", "Liverpool", "Manchester", "Basingstoke"];
cities.unshift("Brighton", "Swansea");
alert(cities);

splice() - To add and remove element anywhere
// first number is position to place new array, second is to remove number of values in that position
var cities = ["London", "Reading", "Liverpool", "Manchester", "Basingstoke"];
cities.splice(2, 0, "Brighton", "Swansea");
alert(cities);

slice() - To copy the element in array
var cities = ["London", "Reading", "Liverpool", "Manchester", "Basingstoke"];
var newCities = cities.slice(1, 4); 
alert(newCities);

Share this

Related Posts