How To Push Array Element In Node.js

Websolutionstuff | Oct-11-2021 | Categories : Node.js

Hello Dev,

In this example we will see how to push array element in node.js example. I will share some example about push object in array in node.js. node.js array element push, push element in array in node.js, node.js array push key value.

So, let's start to implement how to push array element in node.js

Example 1 : push() function

push() is an array function from node.js that is used to add element to the end of an array.

Syntax:

array_name.push(element)
push_array = [2, 4, 6, 8, 10, 12];
  
push_array.push(14);
  
console.log(push_array);

Output :

[ 2, 4, 6, 8, 10, 12, 14 ]

 

 

Example 2 : Key and Value

Now see key and value push in array object.

key_val_arr = [
    {id: 1, name: "dell" },
    {id: 2, name: "hp" },
    {id: 3, name: "apple" }
];
  
key_val_arr.push({id: 4, name: "lenovo"});
  
console.log(key_val_arr);

Output :

[

{ id: 1, name: 'dell' },

{ id: 2, name: 'hp' },

{ id: 3, name: 'apple' },

{ id: 4, name: 'lenovo' }

]

 

Example 3 : unshift() function

In this example add key and value in first position of array object using unshift() function.

key_val_arr = [
    { id: 1, name: "dell" },
    { id: 2, name: "hp" },
    { id: 3, name: "apple" }
];
  
key_val_arr.unshift({id: 4, name: "lenovo"});
  
console.log(key_val_arr);

Output :

[

{ id: 4, name: 'lenovo' },

{ id: 1, name: 'dell' },

{ id: 2, name: 'hp' },

{ id: 3, name: 'apple' }

]

 


You might also like :

 

Recommended Post
Featured Post
How To Send Email Using Markdown Mailable Laravel 9
How To Send Email Using Markdo...

In this article, we will see how to send email using markdown mailable laravel 9. we will learn laravel 9 to s...

Read More

Aug-05-2022

How To Open Datepicker Popup In Angular 15 Material
How To Open Datepicker Popup I...

In this tutorial, I will guide you through the process of opening the datepicker popup in the Angular 15 Material framew...

Read More

Jul-10-2023

How to Get All Routes in Laravel 10
How to Get All Routes in Larav...

Hey there! This tutorial guides you through the process of retrieving a comprehensive list of all routes in a Larav...

Read More

Dec-13-2023

How to Get Soft Deleted Records in Laravel 10
How to Get Soft Deleted Record...

Hey there! Ever wondered how to recover deleted data in Laravel 10 without much hassle? Well, you're in luck! I'...

Read More

Nov-27-2023