Reputation: 1840
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
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
Reputation: 88
Try this :
function replace(l) {
return l.splice("new value",1);
};
var x = replace(arr);
Upvotes: -1
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
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