Add an item to the beginning of an array
Sometimes you might need to add an item to an array. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, this is the most straightforward method to add an item to an array.
There are several different methods that javascript has for array manipulation, depending on what you want to achieve. In this particular example, we will be showing you the method to add to the beginning of an array. To do this, we will be using the unshift() method. The unshift( ) method is similar to the push( ) method except that instead of adding items to the end of the array, it adds items to the beginning of the array. Don't confuse it with the unshift( ) since unshift will delete the first element of the array.
Sometimes you might need to add an item to the beginning of an array. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to add an item to the beginning of an array.
Strategy to adding an item at the beginning of an array is straight forward and involves only one step: We will use is the built in JavaScript array function "unshift( )". The javascript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. The number of arguments to the unshift ( ) method is same as the number of elements you want to add at the beginning of the array.
example
array.shift( item_1, item_2, ... itemNn ) ;
Unshift( ) returns the new length of the array after inserting the arguments at the beginning of the array.
var item_list = [ "had","a","little","lamb" ] ; item_list.push( "Mary" ) ;
Returns :
[ "Mary","had","a","little","lamb" ]