How can the following operation be done without mutating the array:
let array = [\'item1\'];
console.log(array); // [\'item1\']
array[2] = \'item2\'; // array is
Here is how I'd like to do it:
function update(array, newItem, atIndex) {
return array.map((item, index) => index === atIndex ? newItem : item);
}
Generally, Array-spread operation produces few temporary arrays for you, but map
doesn't, so it can be faster. You can also look at this discussion as a reference