Reputation: 3527
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?
Upvotes: 56
Views: 50564
Reputation: 27242
Will the sort and filter functions change the original array
For sort() method, Answer is Yes
but for filter() method answer is No
.
Let me explain with an example :
// Original Array
const arr = [5, 4, 3, 2, 1];
// Sorting array values and assigned in a variable.
const sortedArr = arr.sort((a, b) => a-b);
// Original array modified.
console.log(arr); // [1,2,3,4,5]
// New variable with sorted array.
console.log(sortedArr); // [1,2,3,4,5]
To prevent the original array to get modified, We can use to[Operation]
that return a new collection with the operation applied (This is currently at stage 3, will be available soon).
const arr = [5, 4, 3, 2, 1];
const sortedArr = arr.toSort((a, b) => a-b);
console.log(arr); // [5, 4, 3, 2, 1]
console.log(sortedArr); // [1, 2, 3, 4, 5]
Upvotes: 1
Reputation: 2632
Or from ES6:
const a = [1, 2, 3];
const b = [...a].sort();
Upvotes: 2
Reputation: 141
Yes it modifies the original array.
const a = [1, 2, 3];
const b = a.sort();
const c = [...a].sort(); //es6 feauture similar to slice(0)
console.log(a === b); // true
console.log(a === c);//false
Upvotes: 5
Reputation: 100486
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();
Upvotes: 23
Reputation: 2533
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 } ]
Upvotes: 76