Replace array value from a specific position in JavaScript


To replace value from a specific position, use splice() in JavaScript. Following is the code −

Example

var changePosition = 2
var listOfNames = ['John', 'David', 'Mike', 'Sam','Carol']
console.log("Before replacing=");
console.log(listOfNames);
var name = 'Adam'
var result = listOfNames.splice(changePosition, 1, name)
console.log("After replacing=");
console.log(listOfNames)

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo14.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo154.js
Before replacing=
[ 'John', 'David', 'Mike', 'Sam', 'Carol' ]
After replacing=
[ 'John', 'David', 'Adam', 'Sam', 'Carol' ]

Updated on: 12-Sep-2020

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements