How to Push New Items in JavaScript Array

Push New Items in JavaScript Array, this is the most simple statement that can be achieved with a JavaScript array. This is also very useful in order to build Arrays on the fly.

Now let’s see a very basic example where we will be pushing a data point into an Array

Array of Number

// Simple Example to push numbers and strings into an Array
var Numbers = [1,2,3,4,56];

console.log(Numbers)
Numbers.push(22);
Numbers.push(95);
console.log(Numbers);

Array of String

var Strings = ['Car','Bus','Truck','Rocket']
Strings.push('Auto','Bike');
console.log(Strings);

Now let us insert some JSON data into a JSON Array.

Push into JSON Array

var student = [
{
name: 'Shiv',
id: '1111',
},
{
name: 'Cane',
id: '1331',
},
{
name: 'Ranch',
id: '2211',
},
{
name: 'Reco',
id: '1441',
},
];

student.push({
name: 'Zeni',
id: '1365',
});

console.log(student);

Merging Arrays using Push using apply()

If the length of the Second Array is not too large then you can go ahead and use apply() method in order to merge two arrays.

// Merging Two Arrays into One
var People1 = ['Zen','Ken','Den'];
var People2 = ['Yen','Brat'];

// Merging the first Array into the Second
Array.prototype.push.apply(People1, People2);
console.log(People1)

You can find all these running together out here below. Have a look at the code for each.

Check out all the other posts on JavaScript Essentials to get a Grasp of these JavaScript Utilities.


Originally published at The Web Juice.