'Does .sort function change original array?
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?
Solution 1:[1]
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();
Solution 2:[2]
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.
Solution 3:[3]
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
Solution 4:[4]
Or from ES6:
const a = [1, 2, 3];
const b = [...a].sort();
Solution 5:[5]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Max Base |
| Solution 2 | jfriend00 |
| Solution 3 | SUSEENDHAR LAL |
| Solution 4 | Adrian Bartholomew |
| Solution 5 | Rohìt JÃndal |
