user2394156
user2394156

Reputation: 1840

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?

Upvotes: 3

Views: 1245

Answers (4)

Vic
Vic

Reputation: 8961

You could take advantage of Object.assign and do something like:

const arr = [1, 2, 3, 4, 5];
const updatedArr = Object.assign([], arr, {1: 'myNewValue'});

console.log(arr); // [1, 2, 3, 4, 5]
console.log(updatedArr); // [1, "myNewValue", 3, 4, 5]

Upvotes: 2

Shoaib Khan
Shoaib Khan

Reputation: 88

Try this :

function replace(l) {
    return l.splice("new value",1);
};
var x = replace(arr);

Upvotes: -1

Akshay
Akshay

Reputation: 805

You can use map function to achieve this

var arr = [1,2,3,4,5,6,7,89];

arr.map(function (rm) {
    if (rm == 2) {
        return 3
    } else {
        return rm
    }
})

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1074048

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.

Upvotes: 6

Related Questions