Home > Article > Web Front-end > Is JavaScript\'s Array.sort() Method Stable Across All Browsers?
Introduction
Array sorting is a fundamental operation in JavaScript. However, the stability of the Array.sort() method varies across different browsers.
ECMA Script and Stability
The ECMA Script specification does not define a specific sorting algorithm or specify whether the sort should be stable. This means different browsers may implement different approaches, resulting in varying stability characteristics.
Stability Across Specific Browsers
Example Test Case
To demonstrate the stability of the sort method, a test case involving pairs of values can be created:
<code class="javascript">function Pair(_x, _y) { this.x = _x; this.y = _y; } function pairSort(a, b) { return a.x - b.x; } var check = []; for (var i = 0; i < 100; ++i) { check.push(new Pair(Math.random() * 3 + 1, ++y)); } check.sort(pairSort);</code>
If the sort is stable, the values will be sorted based on their x values first, and then by their y values, such that the original order of values with the same x value is preserved. Conversely, an unstable sort may result in different orders for values with the same x value.
The above is the detailed content of Is JavaScript\'s Array.sort() Method Stable Across All Browsers?. For more information, please follow other related articles on the PHP Chinese website!