Sorting arrays can yield varying results depending on the browser being used

The variations in output between Chrome 70.0, Chrome 69.0, and Firefox 63.0 for the same code are puzzling.

var arr = [1,2,43,1233,5546,33,6,11];
arr.sort(() => -1); //[11, 6, 33, 5546, 1233, 43, 2, 1]
arr.sort(() => 1); //[1, 2, 43, 1233, 5546, 33, 6, 11]

Chrome 70.0 https://i.sstatic.net/w9QZw.png


Chrome 69.0

https://i.sstatic.net/SFLou.jpg


Firefox 63.0 https://i.sstatic.net/bmIPu.png

Answer №1

With the release of Chrome 70, a significant change was made to its sorting algorithm, switching to a stable one. This means that identical elements are now sorted in the same order they appear in the input [0].

Exciting news! Array.prototype.sort is now stable in @v8js v7.0 / Chrome 70! 🎉

Previously, V8 utilized an unstable QuickSort for arrays containing over 10 elements. The new implementation now employs the stable TimSort algorithm. [1]

[0] https://en.wikipedia.org/wiki/Sorting_algorithm#Stability

[1] https://twitter.com/mathias/status/1036626116654637057?lang=sk

Answer №2

This particular issue stems from a mathematical problem, as the comparator provided is not a valid general contract. Therefore, it is unreasonable to expect a "regular result."

if A > B then B < A must hold true
if A > B then NOT (B > A) must be the case
if A > B and B > C then A > C must be true

However, when the comparator is () => 1, the situation arises where A > B and B > A simultaneously, which does not make logical sense!

For your information, in Java, a warning is issued for this specific scenario, and in some instances, failure to adhere to it can result in a "Comparison method violates its general contract" exception:

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y

https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying one out of two elements when the button is clicked

Trying to implement two buttons on the parent component, each displaying a different component - one for itemlist and the other for itemlist2. Struggling to get it right, even after following an example at https://codepen.io/PiotrBerebecki/pen/yaVaLK. No ...

Issue with implementing bootbox and jQuery.validator for AJAX login form collaboration

Here's a fiddle link that showcases the issue I'm facing. The problem arises when I try to Sign In on an empty modal form. The validator should highlight any fields in error and proceed to submit the form once the validation is successful. I&ap ...

Utilizing a Grunt task to inject code into an AngularJS file

Hey there! I'm currently looking for a way to add some code into my app.js file that will only execute when I run the "grunt serve" task. This code is just two lines of javascript that should be present when I test the app on my local environment. Unf ...

How to dynamically change the content of the <header> in Nextjs depending on the loaded component

I recently finished creating a app/components/Header.js component. export function Header() { return <> <header className="w-full h-14 grid grid-cols-12 bg-gray-50 text-black dark:bg-gray-900 dark:text-white"> <div ...

Unable to retrieve nested element from its parent

I am facing an issue with accessing a child element's method from the parent element using ref='menu'. When I try to call $refs.menu.show in a button element within the Vue app, it works fine. However, when I try to do the same in a photo el ...

When transitioning to the production environment, Nuxt.js fails to load images

I am currently working on developing a rather large app. Everything was running smoothly in the development environment without any errors. However, upon switching to the production environment, I started encountering numerous errors. Nuxt seems to be havi ...

Retrieving data from Firebase using JavaScript to extract object details

I've been trying to understand this issue by looking at similar questions, but I'm still stuck. This is the response I get from Firebase: '{"users":[null,{"-JFhOFSUwhk3Vt2-KmD1": {"color":"White","model":"650i","year":"2014","make":"BMW"} ...

Unable to execute a join operation in TypeScript

I have an array of objects listed below var exampleArray = [{ "isAvailable": true, "receipent": [{ "id": "a6aedf0c34", "receipentName": "ABC" }, { "id": "a6aedbc34" ...

The dimensions on Next.js pages exceed those of the viewport by a significant margin

I have recently encountered a perplexing issue where the dimensions of my webpage appear to be 2.7 times larger than the viewport, even when there is no content or styles applied. The strange part is that it seems as though the page has been scaled up, eve ...

Using the inline calendar feature of Bootstrap 3 Datepicker to easily select and capture dates

I've been struggling to extract the selected date from my bootstrap 3 datepicker, and despite attempting to follow the documentation, I still can't grasp it. Here's what I tried: <div id="datetimepicker"> <i ...

Is it normal for e.target.result to only work after two or three tries?

Attempting to resize an image on the client side before sending it to the server has been challenging for me. Sometimes, the image does not align correctly with the canvas used for resizing. I have noticed that I need to send the resized image at least tw ...

The use of 'process.argv' and 'process.argv.slice(1)' does not seem to be functioning properly within Cypress

Currently, I am utilizing Cypress with JavaScript for my automation testing needs. My current task involves storing the user-passed command to run a script. Allow me to elaborate: Below is an excerpt from my package.json file: "scripts": { &q ...

Sending data from multiple HTML table rows at once to a Django model

After a user selects items from a list, they can submit the selected items to be saved in a table. The table is dynamically rendered using JavaScript and the data comes from a Map with keys as primary keys and values as descriptions and prices. function d ...

Sending cookies via POST/GET request with Credentials is not functioning

Greetings, despite the numerous duplicates of this inquiry, my attempt to solve it has been unsuccessful. Therefore, I am initiating a fresh discussion. Aside from utilizing axios, I also experimented with fetch but encountered similar outcomes. On the b ...

What is preventing me from adding content to a <p> element?

I'm currently developing a ToDo list web application and I'm working on retrieving the information from 4 text boxes to create the content for each ToDo item. However, when I attempt to link the elements generated from the form, I encounter the ...

Tips for globally overriding MUIv4 class in JSS for nested themes

Summary: Skip to EDIT2 MUIv4 has generated the following classes for me based on my nested theming: <label class="MuiFormLabel-root-121 MuiInputLabel-root-113 MuiInputLabel-formControl-115 MuiInputLabel-animated-118 MuiInputLabel-shrink-117 M ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

Express.js Failing to Send Response Following POST Request

This is the function I have on the back end using express: // Function to register a new user exports.register_user = function(req, res) { var portalID = req.body.portalID; var companyName = req.body.companyName; var password = req.body.passwo ...

Troubleshooting Cross-Origin Resource Sharing problem with Stripe API integration in Angular

I am diving into the world of Stripe API and CORS for the first time. I've set up a POST request from Angular to my Node.js server. Since the client origin differs from the server destination, I have implemented CORS on the server side. When inspectin ...

Tips for Configuring a Nestjs Query Using TypeORM to Retrieve Several Entries

When I send this specific URL from my Angular application: http://localhost:3000/api/skills?category_id=2 The main issue revolves around how to modify the code in order to successfully retrieve all skills with a category_id of 2. It is important to note ...