0

Take:

let array = [ ['whatever', 3], ['1st', 1], ['2nd', 1] ]

Now if I sort it using:

array.sort((a,b) => a[1] - b[1])

Will I always end up with:

[ [ '1st', 1 ], [ '2nd', 1 ], [ 'whatever', 3 ] ]

Meaning, is 1st encounter of value of 1 always guaranteed to end up before 2nd encounter which would itself end up before 3rd encounter etc?

d9ngle
  • 1,303
  • 3
  • 13
  • 30

3 Answers3

1

What you're after is a 'stable' sort, and no, Array.prototype.sort does not support this. Good news though, it's just around the corner in ECMAScript 2020. See the introduction here. Namely:

Other updates include requiring that Array.prototype.sort be a stable sort

As for how long it will take to implement in node.js after specification is released, I cannot find any documentation to that effect.


Edit: Even more good news.

Thank you @d9ngle for mentioning https://v8.dev/blog/array-sort. This shows that the v8 engine, as of version 7, supports stable sorting. Node.js runs on v8. So as long as your version of node is up to date enough, Array.prototype.sort will be stable.

To find out which v8 version you are running, see here.

pwilcox
  • 5,542
  • 1
  • 19
  • 31
0

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers respect this.

The answer is: it depends on where you are running the code.

See Array sort description

rodrigoap
  • 7,405
  • 35
  • 46
0

Yes, Array sort() method always keep the first encountered value before the second encountered value.

you can run this snippet on all browsers

https://jsbin.com/pesuwed/edit?js,console

var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 },
  { name: 'Sharp', value: 37 },
];

var items1 = [
  ['Edward', 21],
  ['Sharpe', 37],
  ['And', 45],
  ['The', -12],
  ['Magnetic', 13],
  ['Zeros', 37],
  ['Sharp', 37],
];

// sort by value
var sortedArray = items.sort(function (a, b) {
  return a.value - b.value;
});

var sortedArray1 = items1.sort(function (a, b) {
  return a[1] - b[1];
});

console.log(sortedArray);
console.log(sortedArray1);
  • There is a big difference between data outputting as expected and data being GUARANTEED to be output as expected. To address the latter, you have to consult source documentation. – pwilcox Aug 19 '19 at 17:56