Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Replace array value from a specific position in JavaScript
To replace a value at a specific position in a JavaScript array, you can use the splice() method or direct index assignment. Both approaches modify the original array.
Using splice() Method
The splice() method removes elements and optionally adds new ones at a specified position.
Syntax
array.splice(index, deleteCount, newElement)
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);
console.log("Removed element:", result);
Before replacing: [ 'John', 'David', 'Mike', 'Sam', 'Carol' ] After replacing: [ 'John', 'David', 'Adam', 'Sam', 'Carol' ] Removed element: [ 'Mike' ]
Using Direct Index Assignment
You can also replace array elements by directly assigning a new value to a specific index.
var fruits = ['apple', 'banana', 'orange', 'grape'];
console.log("Before replacement:");
console.log(fruits);
// Replace element at index 1
fruits[1] = 'mango';
console.log("After replacement:");
console.log(fruits);
Before replacement: [ 'apple', 'banana', 'orange', 'grape' ] After replacement: [ 'apple', 'mango', 'orange', 'grape' ]
Comparison
| Method | Returns Removed Elements? | Can Replace Multiple? | Performance |
|---|---|---|---|
splice() |
Yes | Yes | Slower (shifts elements) |
| Direct assignment | No | No (one at a time) | Faster |
Multiple Replacements with splice()
You can replace multiple consecutive elements using splice():
var numbers = [1, 2, 3, 4, 5, 6];
console.log("Original array:");
console.log(numbers);
// Replace 2 elements starting from index 2
numbers.splice(2, 2, 'A', 'B');
console.log("After replacing 2 elements:");
console.log(numbers);
Original array: [ 1, 2, 3, 4, 5, 6 ] After replacing 2 elements: [ 1, 2, 'A', 'B', 5, 6 ]
Conclusion
Use splice() when you need to know what was removed or replace multiple elements. For simple single replacements, direct index assignment is faster and more straightforward.
Advertisements
