user2394156 user2394156 - 1 year ago 87
Javascript Question

How do I replace an array element without modifying the original array and creating copy?

I'm trying to create a pure function that receives an array as parameter and now I want to replace an element at a given index without modifying the provided array argument.

Basically I'm looking for something like this:

export const muFunc = (arr) => {
return arr.replaceElementAt(1, 'myNewValue'); // This doesnt modify arr at all

How can I do that?

Answer Source

Simply copy the array. A simple way to do that is slice:

export const muFunc = (arr) => {
    var newArray = arr.slice();
    newArray[1] = 'myNewValue';
    return newArray;

From a comment on the question:

As the topic says - I'm trying to find out if it's possible without creating a copy of the array

No it's not possible — well, not reasonably. You have to either modify the original, or make a copy.

You could create proxy object that just returns a different value for the "1" property, but that seems unnecessarily complicated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download