Reputation: 275
I have this (in Javascript):
function f(n){
var arr = (''+n).split();
var sortedArr = arr;
sortedArr.sort();
}
When I return arr and sortedArr, they are both sorted. Why is this? Shouldn't the .sort method only sort sortedArr here?
Upvotes: 0
Views: 143
Reputation: 870
Using Array.prototype.slice, will fix the issue.
function f(n){
var arr = (''+n).split();
var sortedArr = arr.slice();
sortedArr.sort();
}
The reason is that arrays and objects in javascript are references and hence mutable.
When you assign, sortedArr=arr;
You're actually copying the reference not the values. i.e. like
if arr is stored at address 1267, then sortedArr will also point to 1267 now, instead of copying the values at different location.
While, when we are doing sortedArr=arr.slice();
it is actually copying the values to other location suppose 1367 and hence pointing sortedArr to a different storage location.
And I guess its quite evident that, in case the values are copied by reference, changing the values through any reference will reflect a change in the other one as well.
Upvotes: 2
Reputation: 386
Kindly look up the difference between primitive data types and referential data types. Objects are referential data types. (Array is an object). If u expecting to create a new copy, then u should use:-
let new_obj = JSON.parse(JSON.stringify(objname))
let new_arr = arr1.slice()
See this example:-
let a1 = [1, 123, 10, 20, 30];
let a2 = a1.slice();
a2[0] = 0;
console.log(a1, a2);
console.log(a1.sort(), a2.sort());
Also, take care while passing referential data types as params. U will run into this problem again.
Upvotes: 1