Table of Contents
Different methods to add items to array in Node.js
In this article, we will how to add items to array in Node.js and make use of three methods - push, unshift and concat - to achieve this
Use the push method
To add items to array, the first method that can be used and is more intuitive is the
push method. With this method, you can more than one element or item to the array, and also, it returns the updated length of the array.
Let’s show the
push method by update an array of math scores and logging the array before and after the addition of the new score by the
let scores = [34, 56, 78, 93, 42, 89, 55]; console.log("The array before 'push' method operation\\n", scores); scores.push(45); console.log("The array after 'push' method operation\\n", scores);
The array before 'push' method operation [ 34, 56, 78, 93, 42, 89, 55 ] The array after 'push' method operation [ 34, 56, 78, 93, 42, 89, 55, 45 ]
Let’s add more than one item and store the return value of the
let scores = [34, 56, 78, 93, 42, 89, 55]; push = scores.push(34, 67, 32); console.log(push); console.log(scores);
10 [ 34, 56, 78, 93, 42, 89, 55, 34, 67, 32 ]
The first line shows the length of the array (10) which is verifiable by the array logged below it.
Use the unshift method
However, if we need to add the items to the beginning of the array, we can’t make use of the
push method, that’s where unshift method comes in.
unshift method, we can add items to array to the beginning of it. Just like
push, it returns the new length of the array and can add more than one element to the array.
Let’s illustrate this by adding new (crucial) tasks to the beginning of the
Use the concat method
Instead of adding singular elements, we might have all the items we want inside an array that way we can add an array to another array. To carry out this operation, we can make use of the
unshift, this method creates (or returns) a new array with the element of the elements of both arrays.
Let’s add items to array by merging two data arrays (
femiData) and log the result of the array merge.
Depending on how you want to add items to array in node.js, you have different methods for that. If you want to add items to back of the array, the
push method is there, and if you want to add items to the front of the array, the
unshift method works for you. However, if you want to add another array to an array, you can make use of the