I have that code:
arr = arr.sort(function (a, b) {
return a.time>b.time
})
Do I need to redefine arr or it is possible just to call sort function? like this:
arr.sort(function (a, b) {
return a.time>b.time
})
Will the sort and filter functions change the original array?
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
fill() method changes some or all items in the array into the value being passed in.
To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.
push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements. slice() copies a given part of an array and returns that copied part as a new 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 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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With