Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a need to add or prepend elements at the beginning of an array.

For example, if my array looks like below:

[23, 45, 12, 67] 

And the response from my AJAX call is 34, I want the updated array to be like the following:

[34, 23, 45, 12, 67] 

Currently I am planning to do it like this:

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

Is there a better way to do this? Does JavaScript have any built-in functionality that does this?

The complexity of my method is O(n) and it would be really interesting to see better implementations.

like image 580
Moon Avatar asked Nov 10 '11 00:11

Moon


People also ask

How do you add a new element to the beginning of an array JavaScript?

unshift() The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

How do you add an element to an array at the beginning?

Answer: Use the unshift() Method You can use the unshift() method to easily add new elements or values at the beginning of an array in JavaScript.

How do you add an element at the beginning & end of this array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

Which array method would you use to add an element to the beginning of an array?

The array unshift method is used to add elements to the beginning of an array. It accepts multiple arguments, adjusts the indexes of existing elements, and returns the new length of the array.


2 Answers

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 an array

A simple diagram...

   unshift -> array <- push    shift   <- array -> pop   

and chart:

          add  remove  start  end    push    X                   X     pop           X            X unshift    X             X   shift           X      X 

Check out the MDN Array documentation. Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called push_front/pop_front) elements, you should never have to implement these yourself.


As pointed out in the comments, if you want to avoid mutating your original array, you can use concat, which concatenates two or more arrays together. You can use this to functionally push a single element onto the front or back of an existing array; to do so, you need to turn the new element into a single element array:

const array = [3, 2, 1]  const newFirstElement = 4  const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]  console.log(newArray);

concat can also append items. The arguments to concat can be of any type; they are implicitly wrapped in a single-element array, if they are not already an array:

const array = [3, 2, 1]  const newLastElement = 0  // Both of these lines are equivalent: const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ] const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ]  console.log(newArray1); console.log(newArray2);
like image 76
meagar Avatar answered Oct 06 '22 07:10

meagar


array operations image

var a = [23, 45, 12, 67];  a.unshift(34);  console.log(a); // [34, 23, 45, 12, 67]
like image 29
Maksym Avatar answered Oct 06 '22 08:10

Maksym