How to Insert Item Specific Index in Array Node JS?

08-Aug-2022

.

Admin

How to Insert Item Specific Index in Array Node JS?

Hi Friends,

This article will provide example of how to insert item specific index in array node js. This article goes in detailed on insert item specific index in array node.js. you can see node js insert item specific index in array. This tutorial will give you simple example of node.js insert item specific index in array using splice function. follow bellow step for insert item specific index in array using for loop in node js.

There are many ways to insert item specific index in array node js. i will give you two examples using splice() and for loop insert item specific index in array node js.

let's see below a simple example with output:

Install Node JS


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Example: 1

index.js

//create array list

myArray = [10,20,30,40]

var i;

/*pos is position which we want to insert at which is index + 1.position two in an array is index 1.*/

var pos = 2; //pos=index + 1

//value to insert

var value = 5

//Initialize from last array element

for(i=myArray.length-1;i>=pos-1;i--){

myArray[i+1]=myArray[i]

}

myArray[pos-1]=value

console.log(myArray)

Output:

[ 10, 5, 20, 30, 40 ]

Example: 2

index.js

//create array list

numberArray = ['one', 'two', 'four', 'five']

//add array in array list

numberArray.splice(2, 0, 'three');

//show output

console.log(numberArray)

Output:

[ 'one', 'two', 'three', 'four', 'five' ]

I hope it can help you...

#Node JS