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
Laravel 8 Multiple Database Connections
Laravel 8 Multiple Database Co...

Hello Freinds, In this tutorial we will see laravel 8 multiple database connections. Today I will give you step by st...

Read More

Apr-19-2021

Laravel 8 Yajra Datatable Example Tutorial
Laravel 8 Yajra Datatable Exam...

In this article, we will see the laravel 8 yajra datatable example tutorial. Datatable provides users to many...

Read More

Sep-30-2020

How to Format Number with 2 Decimal in PHP
How to Format Number with 2 De...

Hey there! If you've ever needed to work with numbers in PHP, you probably know how important it is to format them p...

Read More

Feb-26-2024

How To Use Sweetalert2 In Laravel
How To Use Sweetalert2 In Lara...

Today we will learn how to use sweetalert2 In laravel, You can use sweetalert2 in laravel as well as php, ...

Read More

May-03-2021