javascript array change value at index code example

Example 1: js replace item in array at index

array.splice(indexWhereToReplace, 1, replacement)

// Ex
const arr = [1, 2, 3]
arr.splice(1, 1, 'replacement')
console.log(arr) // [1, 'replacement', 3]

Example 2: replace array element javascript

// Replace 1 array element at index with item 
arr.splice(index,1,item);

Example 3: change index array javascript

Array.prototype.move = function(from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);
};

Example 4: javascript replace array element

array.splice(array.indexOf(valueToReplace), 1, newValue);