DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

How To Push Array Element In Node.js

In this article, we will see how to push array elements in the node js example. Also, learn how to push objects in an array in node.js. The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

So, let's see node js array push key value, and how to push element in the array in javascript.

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)
Enter fullscreen mode Exit fullscreen mode
push_array = [2, 4, 6, 8, 10, 12];

push_array.push(14);

console.log(push_array);
Enter fullscreen mode Exit fullscreen mode

Output:

[ 2, 4, 6, 8, 10, 12, 14 ]
Enter fullscreen mode Exit fullscreen mode

Read Also: Laravel 8 Eloquent whereHas Condition


Example 2 : Key and Value

Now, we will see key and value push in 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);
Enter fullscreen mode Exit fullscreen mode

Output :

[

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

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

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

{ id: 4, name: 'acer' }

]
Enter fullscreen mode Exit fullscreen mode

Example 3: unshift() function

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

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);
Enter fullscreen mode Exit fullscreen mode

Output :

[

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

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

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

{ id: 3, name: 'hp' }

]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another β€œCoder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.