Our first tutorial on JavaScript arrays covered the basics: creating arrays, accessing the contents of arrays, array lengths, and looping through arrays.
In this tutorial, you explore arrays in more depth, and learn how to use various methods of the Array
object to manipulate arrays.
Extracting sections of an array with slice()
You're not limited to accessing single array elements at a time. Thanks to the slice()
method, you can grab a whole section of an array at once. slice()
has the following syntax:
arraySlice = array.slice ( begin [, end] )
The two parameters, begin and end, work as follows:
- begin
- The index of the first element you want to grab. For example, 0 starts from the beginning of the array; 4 starts from the fifth element. You can also use negative numbers to count backwards from the end of the array; for example, -2 starts the slice at the second to last element.
- end
- The index after the last element to grab. For example,
array.slice ( 2, 5 )
extracts the elements at indices 2, 3, and 4 (i.e. the third, fourth, and fifth elements). As with begin, you can use negative numbers to count backwards from the end of the array. You can also leave out end entirely, in which caseslice()
extracts from begin up to the end of the array.
slice()
returns a new array containing the extracted elements.
An example:
var fruits = new Array ( "apple", "pear", "orange", "banana" );
alert ( fruits.slice ( 1, 3 ) ) // Displays "pear,orange"
alert ( fruits.slice ( 0, -2 ) ) // Displays "apple,pear"
alert ( fruits.slice ( 2 ) ) // Displays "orange,banana"
Joining arrays together with concat()
Joining two or more JavaScript arrays together is easy, thanks to the Array
class's concat()
method. The method uses the following syntax:
result = array.concat ( value1, value2, ..., valueN );
concat()
takes one or more values and adds them to the
end of the array, returning the result as a new array. It leaves the
original array untouched.
For example, the following code creates a new array called orangeAndYellowFruits
, containing the array elements of the orangeFruits
array added onto the end of the yellowFruits
array. It then creates another array, orangeYellowAndRedFruits
, containing two additional values - "strawberry" and "raspberry" - tacked onto the end of the orangeAndYellowFruits
array. In all cases, the original arrays remain untouched.
var yellowFruits = new Array ( "banana", "lemon" );
var orangeFruits = new Array ( "orange", "mandarin" );
var orangeAndYellowFruits = yellowFruits.concat ( orangeFruits );
var orangeYellowAndRedFruits = orangeAndYellowFruits.concat ( "strawberry", "raspberry" );
alert ( "Orange and yellow fruits: " + orangeAndYellowFruits );
alert ( "Orange, yellow and red fruits: " + orangeYellowAndRedFruits );
Running the above script displays the following alert boxes:
Orange and yellow fruits: banana,lemon,orange,mandarin Orange, yellow and red fruits: banana,lemon,orange,mandarin,strawberry,raspberry
The values you pass to concat()
can be of any type. If a
value is an array, each element of the array is added to the list. If a
value is not an array, it is added to the list as-is.
Converting an array to a string with toString() and join()
It's often useful to convert an array to a string, especially if you
want to display the array contents. JavaScript gives you two very
similar methods to produce a string from an array: toString() and join()
. Both methods produce one long string containing each of the array elements in order. The only difference is that join()
lets you choose the separator that appears between each element, whereas toString()
always uses a comma as the separator.
toString() and join()
have the following syntax:
result = array.toString ( );
result = array.join ( separator );
If no separator is passed to join()
, a comma is used.
For example:
var fruits = [ "apple", "pear", "orange", "banana" ];
alert ( fruits.toString ( ) ) ; // displays "apple,pear,orange,banana"
alert ( fruits.join ( ) ) ; // displays "apple,pear,orange,banana"
alert ( fruits.join ( "-" ) ) ; // displays "apple-pear-orange-banana"
alert ( fruits.join ( ", " ) ) ; // displays "apple, pear, orange, banana"
Adding and removing elements with unshift()
, shift()
, push()
, pop()
and splice()
JavaScript features some powerful array manipulation methods that let you add and remove individual elements, or a series of elements, from an array.
Unlike other array methods such as concat()
and join()
, the following methods alter the original array.
Adding and removing at the start of an array: unshift()
and shift()
To add one or more elements to the start of an array, use unshift()
:
length = array.unshift ( value1, value2, ..., valueN );
unshift()
takes the value(s) that you want to add, adds
them in order to the start of the array, and returns the new length of
the array. For example:
var fruits = [ "orange", "banana" ];
var newLength = fruits.unshift ( "apple", "pear" );
alert ( fruits ); // displays "apple,pear,orange,banana"
alert ( newLength ); // displays "4"
To remove and return the first element from an array, use shift()
:
element = array.shift ( );
shift()
removes the first element from the start of the array and returns the removed element. For example:
var fruits = [ "apple", "pear", "orange", "banana" ];
var fruit = fruits.shift ( );
alert ( fruits ); // displays "pear,orange,banana"
alert ( fruit ); // displays "apple"
Adding and removing at the end of an array: push()
and pop()
To add one or more elements to the end of an array, use push()
:
length = array.push ( value1, value2, ..., valueN );
push()
takes the value(s) that you want to add, adds
them in order to the end of the array, and returns the new length of the
array. For example:
var fruits = [ "orange", "banana" ];
var newLength = fruits.push ( "apple", "pear" );
alert ( fruits ); // displays "orange,banana,apple,pear"
alert ( newLength ); // displays "4"
To remove and return the last element from an array, use pop()
:
element = array.pop ( );
pop()
removes the last element from the end of the array and returns the removed element. For example:
var fruits = [ "apple", "pear", "orange", "banana" ];
var fruit = fruits.pop ( );
alert ( fruits ); // displays "apple,pear,orange"
alert ( fruit ); // displays "banana"
Summarizing unshift(), shift(), push() and pop()
- unshift()
- Adds elements to the start of an array
- shift()
- Removes 1 element from the start of an array
- push()
- Adds elements to the end of an array
- pop()
- Removes 1 element from the end of an array
Adding and removing in the middle of an array: splice()
The powerful splice()
method lets you add and/or remove one or more elements from any point in an array:
removedElements = array.splice ( index, numberToRemove, [value1][, value2, ..., valueN] );
The parameters and return value of splice()
work as follows:
- index
- The index at which to start adding and/or removing elements from the array. For example, 0 starts at the beginning of the array; 4 starts at the 5th element. You can also use negative numbers to count backwards from the end of the array, so -2 starts from the second-to-last element.
- numberToRemove
- How many elements to remove from the array, starting at index. If you only want to add elements and not remove elements, use
0
for this value, then specify the elements to add as described below. - value1, value2, ..., valueN
- The element(s) to add to the array at index. If you only want to remove elements, simply miss out this parameter.
- removedElements
- An array containing the element or elements removed from the affected array. If you specified a value of
0
for numberToRemove, removedElements will be empty.
Here are some examples of splice()
in action.
Removing two elements from the middle of an array:
var fruits = [ "apple", "pear", "orange", "banana" ];
var removedElements = fruits.splice ( 1, 2 );
alert ( fruits ); // displays "apple,banana"
alert ( removedElements ); // displays "pear,orange"
Adding two elements to the middle of an array:
var fruits = [ "apple", "pear", "orange", "banana" ];
var removedElements = fruits.splice ( 2, 0, "cherry" );
alert ( fruits ); // displays "apple,pear,cherry,orange,banana"
alert ( removedElements ); // displays ""
Replacing two elements with a single, new element:
var fruits = [ "apple", "pear", "orange", "banana" ];
var removedElements = fruits.splice ( 1, 2, "cherry" );
alert ( fruits ); // displays "apple,cherry,banana"
alert ( removedElements ); // displays "pear,orange"
As you can see, JavaScript gives you some powerful ways to manipulate
arrays — you can alter the elements at the start of an array with unshift()
and shift()
, modify the end of an array with push()
and pop()
, and add or remove elements at any point in an array with splice()
.
Whenever an element is added to or removed from the start or middle of an array using unshift()
, shift()
or splice()
,
the indices of the elements after the added or removed element change
appropriately. For example, if an element is added to the start of an
array with unshift()
, the indices of the existing elements in the array increase by 1.
Source ; http://www.elated.com/articles/manipulating-javascript-arrays/