Does .sort function change original array?
Use slice()
to sort a copy of the original array.
var arr =[{time:4},{time:3},{time:6}];
arr.sort(function (a, b) {
return a.time-b.time;
});
will mutate the original array and returns :
[ { time: 3 }, { time: 4 }, { time: 6 } ]
and console.log(arr) returns
[ { time: 3 }, { time: 4 }, { time: 6 } ]
but
var arr =[{time:4},{time:3},{time:6}];
arr.slice().sort(function (a, b) {
return a.time-b.time;
});
returns
[ { time: 3 }, { time: 4 }, { time: 6 } ]
but will not affect the original array.
console.log(arr) returns
[ { time: 4 }, { time: 3 }, { time: 6 } ]
It's a decent question, and let's answer it properly:
const a = [1, 2, 3];
const b = a.sort();
console.log(a === b); // true
there is your answer. The ===
operator for objects will compare memory locations, so it's the same object in memory.
Which is a shame because it would be better if sort created a new array (immutability etc), but in many languages it does not return a new array, but the same array (reordered).
So if you want it to be immutable, you can do:
const a = [1, 2, 3];
const b = a.slice(0).sort();
It sorts the array in place (modifying the array). From MDN:
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.