There are a few methods used for data manipulation in an array.

Concat

The concat() method is used to create a new array based on the items from another existing array. The method accepts arguments that explain what data will be appended to an existing array. If the arguments are skipped, the method will simply create a copy of the original array.

var array1 = ["John", "Smith", "29"];

var array2 = array1.concat("Web Designer", ["Louisville", "KY", "40241"]);

The 2nd array will add "Web Designer" information and an array about "John's" address to the previous array that already contains first name, last name and age.

Slice

The slice() method will create an array that contains one or more items from another array. The method accepts one or two arguments which are the starting and stopping positions of the items to be returned.

If the 2nd argument is skipped, the new array will return all the items between the item marked in the first argument, and the last item there is.

Observe these examples:

var fruits = ["apple", "orange", "banana", "watermelon", "grape"];

alert(fruits.slice(3)); // "watermelon","grape"

alert(fruits.slice(2, 4); // "banana","watermelon","grape"

Negative numbers are accepted but in such a case the positions will be subtracted from the length of the array, let say:

alert(fruits.slice(-2,-1); // "watermelon","grape" (because it is equal as slice(3, 4))

Splice

The splice() method is used to insert new items into existing array and / or deleting old items.

The newly inserted items may be placed into a specific position while at the same time replacing the existing items. That is achieved by passing two or three arguments. The first one is always the starting position, the second one is a number of items to delete and the third one, if any, will be a new item (or items) to be inserted into the array.

Examples below show how this method works:

var cars = ["Toyota", "Volvo", "Fiat"];

// remove item

var new = cars.splice(0, 1);

alert(cars); // Volvo, Fiat

alert(new); // Toyota

// insert 2 items

new = cars.splice(1, 0,  "Ford", "Nissan");

alert(cars); // Volvo, Ford, Nissan, Fiat

alert(new); // empty array

// insert 2 items and remove 1

new = cars.splice(1, 1, "BMW", "Kia");

alert(cars); // Volvo, BMW, Kia, Nissan, Fiat

alert(new); // Ford

Example

The example with arrays manipulation methods in JavaScript:

 

›› go to examples ››