AppDividend
Latest Code Tutorials

Javascript Array push() | Javascript Add to Array

1

Javascript array push() an inbuilt function that adds a new element at the end of an array and returns the new length of an array. The push() method modifies the length of the Array or collection. Arrays in JS are list-like objects whose prototype has methods to perform the traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed.

We can add new items in the Array using the following approach.

  1. Javascript array push() method is used to add items at the end of an array.
  2. Javascript array unshift() method is used to add items at the beginning of an array.
  3. Javascript array splice()  method is used to add elements within the Array.

So, in this example, we will see how we can perform javascript add to array operation.

Understanding Javascript Array push()

Javascript array push() is an inbuilt method that can be used to append a number, string, object, Array, or any value to the Array. JavaScript arrays are used to store multiple values in a single variable. An array data structure can hold many values under a single name, and you can access those values by referring to the index number.

Let us see the syntax of the Javascript Array push() method.

Syntax

array.push(element)

You can use a push() method to append more than one value to an array in a single call.

array.push(item1, item2, item3,...,itemN)

Parameters

Javascript push() method takes the item(s) to add to the Array.

Return Value

It returns Number, representing the new length of the Array.

The push() method can be used with a call() or apply() on objects resembling the arrays. The array.push()  method relies on the length property to resolve where to start inserting the given elements.

If the length cannot be converted into a number, the index used is 0.

It includes the possibility of length being nonexistent, in which case the length will also be created.

Example

data = ['Python', 'Javascript', 'PHP']
len = data.push('Golang')
console.log('The modified array is: ', data)
console.log('The length of modified array is: ', len)

Output

The modified array is:  [ 'Python', 'Javascript', 'PHP', 'Golang' ]
The length of modified array is:  4

 First, we have defined an array and then add a new item called Golang and store the length of the new Array. Then print the mutated Array and its length.

Understanding Javascript Add to Array

Javascript add to Array means we can add any items like integers, strings, arrays, objects, an array of strings, an array of integers, an array of arrays to the Array. Let us take an example of Node.js to understand how to add an item in an array in javascript.

// app.js

const songs = ['Dangerous', 'Thriller'];
const totalSongs = songs.push('Stranger In Moscow');

console.log(totalSongs);

console.log(songs);

See the output.

➜  es git:(master) ✗ node app
3
[ 'Dangerous', 'Thriller', 'Stranger In Moscow' ]

In this example, we have added the third element called “Stanger in Moscow“. After adding an item to the Array, we have printed the mutated Array and its length.

Adding multiple items in the Array

If you have seen the syntax of the Array.push() method, and then you can see that we can add multiple elements as arguments in a single time.

data = ['Python', 'Javascript', 'PHP']
len = data.push('Golang', 'C#', 'Swift')
console.log('The modified array is: ', data)
console.log('The length of modified array is: ', len)

Output

The modified array is:  [ 'Python', 'Javascript', 'PHP', 'Golang', 'C#', 'Swift' ]
The length of modified array is:  6

You can see that we have added three elements in a single time, and all the elements are added in the Array.  The push() function can be called with multiple arguments, which will be appended to the array in order.

Merging Arrays in Javascript using array push()

Let us take an example of how we can merge two arrays.

// server.js

const artists = ['michael', 'elvis'];
const newArtists = ['justin', 'charlie'];

Array.prototype.push.apply(artists, newArtists);

console.log(artists);

See the output.

➜  es git:(master) ✗ node app
[ 'michael', 'elvis', 'justin', 'charlie' ]
➜  es git:(master) ✗

Do not use the apply() method if the second Array (newArtists in the example) is vast, because the maximum number of arguments that one function can handle is limited in practice.

So, apply() will add the second Array into the first Array, and we can see the combined Array by returning the original Array, and in our case, it is artists.

If you want to append the items of one Array to another array, you can use the concat() function of the Array. We can also use the Javascript concat() method to merge the arrays.

See the following code. We have taken an array of Strings.

// server.js

const artists = ['michael', 'elvis'];

artists.push('justin', 'charlie');

console.log(artists); // ['michael', 'elvis', 'justin', 'charlie']

Here, we have added two more artists. Now, see the following code.

// server.js

const artists = ['michael', 'elvis'];
const newArtists = ['justin', 'charlie'];
artists.push(newArtists);

console.log(artists);

See the output.

➜  es git:(master) ✗ node app
[ 'michael', 'elvis', [ 'justin', 'charlie' ] ]
➜  es git:(master) ✗

Here, the third element is an array. So it has added the third item as a whole array. So we can not combine it as we have done it with apply().

We can remove the element from an array using the Javascript pop() method.

Adding Object to Array using Javascript array push()

Javascript push() method is used to add one or multiple elements to the end of an array. The push() function returns the new length of the Array formed. An object can be inserted, bypassing the object as a parameter to this method. The object is hence added to the end of the Array.

Here, See the following code.

// app.js

arrObj = [
  {
    name: 'Krunal',
    age: 26
  },
  {
    name: 'Ankit',
    age: 24
  }
];
arrObj.push({
  name: 'Rushabh',
  age: 27
});
console.log(arrObj);

See the following output.

➜  es git:(master) ✗ node app
[ { name: 'Krunal', age: 26 },
  { name: 'Ankit', age: 24 },
  { name: 'Rushabh', age: 27 } ]
➜  es git:(master) ✗

If you want to add an object in the array then you have to pass an object as an argument and make sure that keys are the same. So, this is How to push both key and value into an Array in Javascript.

Adding Array into the Array using push()

Javascript push() function allows us to push an array into an array. We can add an array into an array, just like adding an element into the Array.

// app.js

arrArray = [
  ['Krunal', 'Ankit'],
  ['Rushabh', 'Dhaval']
];
arrArray.push([
  'Tejash', 'Rajesh'
]);
console.log(arrArray);

See the output.

Javascript Array Push Example | Add Element To Array In JS

If you’re only appending the single variable, then array.push() method works like a charm. If you have to append another array, use the concat() method. This approach is beneficial when you don’t have to modify the original array, and that is why it is standard practice and adapted by the Javascript community.

data = ['Python', 'Javascript', 'PHP']
data2 = ['Java', 'Kotlin', 'Swift']

langs = data.concat(data2)
console.log(data)
console.log(data2)
console.log(langs)

Output

[ 'Python', 'Javascript', 'PHP' ]
[ 'Java', 'Kotlin', 'Swift' ]
[ 'Python', 'Javascript', 'PHP', 'Java', 'Kotlin', 'Swift' ]

Javascript array.concat() is a pure function and does not mutate its original array. Instead, it returns a new Array.  Please make sure here that the concat() function creates a new array. It does not add or appending to an existing array. It simply creates a copy and perform the operation in that copy and return that array.

Javascript array.push.apply() function is also useful to add array into the array.

let arr = ['Python'];
arr.push('Javascript', 'PHP');
arr.push.apply(arr, ['Dart', 'Golang']);
console.log(arr);

Output

[ 'Python', 'Javascript', 'PHP', 'Dart', 'Golang' ]

You can use the push() and apply() function to append two arrays.

Now, from the 2016 update: with spread, you don’t need that apply() method anymore.

let arr = ['Python'];
arr.push('Javascript', 'PHP');
arr.push(...['Dart', 'Golang']);
console.log(arr);

Output

[ 'Python', 'Javascript', 'PHP', 'Dart', 'Golang' ]

You can see that output will be the same, but this way is more concise and appealing to other coders.

Appending Multidimensional Array in Javascript

We can also add a multidimensional array into an array using a js array push function.

See the following programming example.

// app.js
 mulArray = [];
 $data = ['Tejash', 'Rajesh'];
 $info = [35, 40];
 mulArray.push($data, $info);
 console.log(mulArray);

See the output.

➜  es git:(master) ✗ node app
[ [ 'Tejash', 'Rajesh' ], [ 35, 40 ] ]
➜  es git:(master) ✗

There are several methods for appending new elements to the JavaScript array. If you instead want to remove elements from an array in JavaScript, we’ve got an article for that too.

See the following methods.

Adding an element to a specific position in the Array

We can also directly manipulate an array, we will not use any array methods, by referring to the index position within the Array.

Here we add two new elements at specified positions. See the following code example.

// app.js
let list = ["foo", "bar"];
list[2] = "baz";
list[3] = "qux";
console.log(list)

See the following output.

Add an element at specified an index

Adding element at the beginning of the Array

Use unshift() method. It’s like push, except it inserts elements to the beginning of the Array instead of the end.

  1. unshift/push: add an element to the beginning/end of an array.
  2. shift/pop: remove and return the first/last element of an array.

A simple diagram is following,

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

and the chart is the following.

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

Conclusion

JavaScript array push() is a function used to incorporate new HTML elements into an array. By default, the JavaScript push() method will append the new items at the end of the array. After the JavaScript push() function is applied to an array, it will deliver a very specific return value.

A simple example, suppose you have an array of the children of House Stark from Game of Thrones. However, one of the members, Bran, is missing which is funny because it is the King of Six kingdoms. Using the push() method, you could add him by assigning ‘Bran‘ to the array at the index after the last index.

That is it for this tutorial.

Recommended Posts

Javascript array isArray()

Javascript array filter()

Javascript array map()

How To Get Distinct Values From Array

Javascript object values()

Pop Push Shift and Unshift Array Methods in JavaScript

1 Comment
  1. Amit Parmar says

    thanks for the post

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.