How To Push Array Element In Node.js

In this article, we will explore different techniques for adding elements to arrays in a Node.js example. We'll cover the fundamental push() method for appending elements to the end of an array, as well as adding key-value pairs.

Additionally, we'll dive into the unshift() function, which allows you to insert elements at the beginning of an array. These methods are essential for effectively manipulating arrays in Node.js and JavaScript.

Let's delve into how to use push(), key-value pairs, and unshift() to modify and expand arrays in your Node.js applications

Example 1: push() function

push() is an array function in Node.js used to add elements 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, let's explore how to push key-value pairs into an array object.

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

Output :

[

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

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

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

{ id: 4, name: 'acer' }

]

 

Example 3: unshift() function

In this example, we will use the unshift() function to add a key and value at the beginning of the array object.

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

Output :

[

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

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

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

{ id: 3, name: 'hp' }

]

 

Conclusion:

In conclusion, we've learned various techniques for adding elements to arrays in a Node.js context. We explored the push() method, which is invaluable for appending elements to the end of an array.

Additionally, we delved into the process of adding key-value pairs to arrays, and we examined how to use the unshift() function to insert elements at the beginning of an array.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS