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?
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.
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]
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
}
})
Try this :
function replace(l) {
return l.splice("new value",1);
};
var x = replace(arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.