javascript tutorial - [Solved-5 Solutions] Array elements at beginning - javascript - java script - javascript array



Problem:

How to add new array elements at the beginning of an array in JavaScript?

Solution 1:

[23, 45, 12, 67]
click below button to copy the code. By JavaScript tutorial team

And the response from our AJAX call is 34,

[34, 23, 45, 12, 67]


var newArray = [];
newArray.push(response);

for (int i = 0; i < theArray.length; i++) {
    newArray.push(theArray[i]);
}

theArray = newArray;
delete newArray;
click below button to copy the code. By JavaScript tutorial team

Solution 2:

Use unshift . It's like push , except it adds elements to the beginning of the array instead of the end.

  • unshift/push - add an element to the beginning/end of an array
  • shift/pop - remove and return the first/last element of and array

A simple diagram...

   unshift -> array <- push
   shift   <- array -> pop
click below button to copy the code. By JavaScript tutorial team

and chart:

          add  remove  start  end
   push    X                   X
    pop           X            X
unshift    X             X
  shift           X      X
click below button to copy the code. By JavaScript tutorial team

Solution 3:

var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]
click below button to copy the code. By JavaScript tutorial team

Solution 4:

* array_unshift()  -  (aka Prepend ;; InsertBefore ;; InsertAtBegin )     
* array_shift()    -  (aka UnPrepend ;; RemoveBefore  ;; RemoveFromBegin )

* array_push()     -  (aka Append ;; InsertAfter   ;; InsertAtEnd )     
* array_pop()      -  (aka UnAppend ;; RemoveAfter   ;; RemoveFromEnd ) 
click below button to copy the code. By JavaScript tutorial team

Solution 5:

function fn_unshift() {
  arr.unshift(0);
  return arr;
}

function fn_concat_init() {
  return [0].concat(arr)
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Array elements at beginning