Array Methods and Properties
Join the Discussion
Arrays are extremely useful when you have several similar objects that you want to be able to process the same way or to be able to process as a group rather than individually. The Array object itself provides a number of methods that make manipulation of the whole group of objects or specific objects within the group much easier.
- concat(secondarray) will concatenate the elements of the second array onto the end of the original array effectively joining two arrays together.
- join(separator) converts the array into a string by placing the contents of the elements one after the other with the specified separator in betwee. If no separator is specified then a comma will be used.
- pop() removes the last element from the array making the array smaller. The removed element is returned from the method call allowing it to be processed.
- push(element) adds an element to the end of the array.
- reverse() reverses the order of the elements within the array.
- shift() similar to pop() but removes and returns the first element in the array rather than the last.
- slice(start,end) creates a new array containing a subset of the elements from the original array. The start and ennd values are numbers indicating which elements to extract counting from the start of the array iif the numbers are positive or from the end of the array if they are negative. If an end value is omitted then the elements from the start position to the end of the array will be extracted.
- sort(compareFunction) will sort the elements in the array into any desired order. If no compare function is specified then the elements will be treated as strings and sorted into ascending order. By providing an appropriate compare function you can set whatever sort order you require.
- splice(position,number,element1,...) allows you to insert, delete, or replace elements from anywhere within the array. The specified number of elements from the specified position will be removed from the array and will be replaced with the elements specified in the third and subsequent parameters.
- unshift(element) similar to push except that the new element gets added to the start rather than the end of the array.