In this tutorial, we will demonstrate the javaScript array push() function by examples.
Sometimes you want to push a single or multiple items in an array. So you can use the JavaScript push() method to add an item in an array.
The javaScript push() method is used to add a new element to the end of an array.
Note: javaScript push() array method changes the length of the given array.
array.push(item1, item2, ..., itemX)
javaScript push array method examples tutorial, you will learn the following:
Here, you will learn how to add a single item into a given array. Let’s take an example.
Suppose we have an array that’s the name arrNum, and it contains four elements inside it, see below:
var arrNum = [
"one",
"two",
"three",
"four"
];
If you want to add the single item into the arryNum array. So you can use the push() method of javaScript like below:
var arrNum = [
"one",
"two",
"three",
"four"
];
arrNum.push("five");
console.log( arrNum );
["one", "two", "three", "four", "five"]
If you want to add multiple items and elements into a given array. You can use the below example.
Let’s take a new example of how to add multiple items into a given array.
Suppose we have an array that names arrMul and it contains five value and we want to add five more or N value into it, so use the below example
var arrMul = [
"one",
"two",
"three",
"four"
];
arrMul.push("six","seven","eight","nine","ten");
console.log( arrMul );
["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
If you want to merge two array in javaScript. So you can use the apply() method.
Suppose, you have two array and you want to merge, let’s take an example:
const numbers = ['1', '2'];
const newNumbers = ['3', '4', '5'];
Array.prototype.push.apply(numbers, newNumbers);
console.log(numbers);
Note: If the second array (newNumbers in the example) is huge, do not use the apply () method, because the maximum number of arguments a function can handle is limited in practice.
["1", "2", "3", "4", "5"]
If you want to add array into another array. Let’s see the below example:
var arr = [ ["one"], ["two"], ["three"], ["four"], ["five"] ];
arr.push( ["six"], ["seven"], ["eight"], ["nine"], ["ten"] );
console.log(arr);
[Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1)]
How to push an array of the object into array.
Let’s take a simple example of this, suppose we have one an arrayObj and it contains two object. If you want to add one more object into the arrayObj. So you can see the below example.
arrayObj = [
{
name: 'xyz',
email: 'xyz@g.com'
},
{
name: 'abc',
email: 'abc@g.com'
}
];
arrayObj.push({
name: 'test',
email: 'test@g.com'
});
console.log(arrayObj);
In this article, you have learned, how to add single and multiple items into a given array and how to merge two array. And also learn how to add array into another array.
#javascript #webdev