replace element at index in array in javascript

To replace an element at a specific index in a Javascript array, you can make use of the splice() method. The splice() method modifies the original array by adding or removing elements from it. Here is an example code snippet that replaces an element at index i in an array arr with a new element:

arr.splice(i, 1, newElement);
30 chars
2 lines

In the above code snippet, the first argument to splice() is the index where the replacement is to be made. The second argument specifies the number of elements to be removed, which in this case is 1. Finally, the third argument is the newElement that should be inserted at the specified index.

Here is an example usage of this code snippet:

let arr = ["apple", "banana", "orange", "peach"];
let i = 2; // index of orange
let newElement = "grapefruit";
arr.splice(i, 1, newElement); // replace orange with grapefruit
console.log(arr); // Output: ["apple", "banana", "grapefruit", "peach"]
247 chars
6 lines

In the above example, we replace the element at index 2 (which is "orange") with a new element "grapefruit". The resulting array is ["apple", "banana", "grapefruit", "peach"].

gistlibby LogSnag