Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
Prosto Trader Avatar asked Jun 06 '14 05:06

Prosto Trader


People also ask

Does .sort 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.

Which array method changes the original array?

fill() method changes some or all items in the array into the value being passed in.

How do you sort an array without changing original?

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.

How do you change an original array?

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.


3 Answers

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 } ]

like image 68
LexJacobs Avatar answered Oct 10 '22 17:10

LexJacobs


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.

like image 8
jfriend00 Avatar answered Oct 10 '22 16:10

jfriend00


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();
like image 20
Alexander Mills Avatar answered Oct 10 '22 15:10

Alexander Mills