2

If the two elements have the same property value on which we sort the array then how javascript order them i mean if you have this array for example :

let array = [{id:0,name:"sam",age:"20"},
             {id:0,name:"john",age:"21"},
             {id:1,name:"fred",age:"30"}]

let's suppose that i want to sort this array by id ascending then how can i know which one will appear first :

{id:0,name:"sam",age:"20"}

OR

{id:0,name:"john",age:"21"}

2 Answers2

2

Up until now the Array.prototype.sort was not a stable sort because there was no mentioning for it in the spec so actually there was no guaranty for a stable (consistent) order.

Though recently, the spec has changed and the V8 engine implemented it as a stable sort.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
1

I realized after answering that this is a duplicate. See my answer to the dupetarget. Briefly: As of ES2019, Array#sort is stable, so in your example "sam" will remain before "john". Prior to ES2019, that wasn't necessarily true, they could have had their order reversed.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875