Monday, September 09, 2013

JavaScript: Slicing an Array

Have you ever wanted just a sub section of an array? Well, with slicing an array you can do just that.

Suppose I have an array

var myArray = [1,2,3,4,5];

and I want the first 3 elements, I can do the following

myArray.slice(0,3);

which return an array with the first 3 elements

[ 1, 2, 3 ]

This does not modify the original array in any way, it just returns a new array

The function slice has the following signature,

slice ( beginIndex, endIndex ) where the index is zero based i.e. the first element in a an array starts at index 0.

You could also access the array from the end using negatives indices for example,

myArray.slice(-3, -1);

returns

[ 3, 4 ]

Next we will look at splice......until next time!