I am using .map() on an array inside a function. I am not modifying the array itself (arr = arr.map(...)), but rather creating a new array (var arr2 = arr.map(...)).
Yet, this still modifies the original arr outside my function (which I don't want). How can I preserve?
var arr = [{prop: 1}];
myFunction(arr);
console.log(arr[0].prop); // returns 2, I want it to return 1
function myFunction(arr) {
var arr2 = arr.map(obj => {
obj.prop = 2;
return obj;
});
console.log(arr[0].prop); // returns 2
}
obj.prop = 2modifies the object in the array, sinceobjis a reference to the same object, not a clone.