What causes Array.prototype.sort to function differently in Chrome?

As I was attempting to organize an Array, I observed a discrepancy between the behavior in Chrome V79 and Firefox Dev Edition V72 (both desktop versions).

Here is the test:

console.log([4, 2, 5, 1, 3].sort((a, b) => a>b));
console.log(Array.prototype.sort.call([4, 2, 5, 1, 3], (a, b) => a>b));

In Firefox Dev, I see this result:

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

However, in Chrome, I am presented with this result:

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

When I pass the same array with var, a different result appears:

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

The Array gets sorted and the variable gets rewritten, but the returned version of the Array remains unsorted. This leads to no sorting when passing the Array directly without any var.

According to MDN's reference page, shouldn't it return the sorted Array?

Why is there a difference?

Note: In the Example Images, both examples involve me practicing the call function and were mistakenly left in. Please disregard them as they are identical.

Answer №1

In response to the feedback given in the comments, it is essential that the sorting function you provide should adhere to the following rules:

  • Return a positive number if a is greater than b
  • Return a negative number if b is greater than a
  • Return 0 if they are equal

Hence, instead of using a > b, a straightforward expression like a - b can be utilized for ascending sort order:

console.log([4, 2, 5, 1, 3].sort((a, b) => a-b));

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

jquery detecting changes and enabling readonly attribute

I need to trigger an event with the "on change" functionality for a read-only input using jQuery. After that, I want to add some HTML content below it. Essentially, whenever the read-only input is modified, the HTML code should be appended. Please take a ...

How can we create a PHP function that splits an array by detecting every blank line?

I am currently in the process of creating a script that will retrieve the contents of a saved text file, convert them into an array, and then store the data in a database. I have successfully implemented the file upload feature and can also open the file w ...

Expressjs router.get('/') not firing as expected

I am facing an issue where I cannot access my express application's home page using the '/' route pattern. Instead, it only works with '/index'. My express version is 4.6. Even after trying app.use('/*', router), my appl ...

Using Typescript with d3 Library in Power BI

Creating d3.axis() or any other d3 object in typescript for a Power BI custom visual and ensuring it displays on the screen - how can this be achieved? ...

Problem with Jsdom retrieving document

I am struggling to utilize jsdom for loading a local HTML file. Here is the code snippet: var config = { file: "filename", scripts: ["node_modules/jquery/dist/jquery.min.js"], done: function(err, window){ con ...

Expanding and Shrinking Text Areas with Jquery

I am looking to create a textarea that comes preloaded with content. The height of the textarea should adjust to auto when there is content present, but switch to a height of 4.2rem when it is empty. Additionally, I want the textarea to dynamically increas ...

Guide to fetching data from database based on selection in dropdown list using PHP and MySQL

Is there a way to retrieve information from a database and automatically populate a textarea field based on the option selected from a dropdown list using an onSelect event? You can view a screenshot of my form here. Basically, I want the description ass ...

Creating a Nuxt project and integrating the Axios module

I'm running into an issue where I'm not receiving any data from my Axios async calls. I've configured my calls in my Nuxt config as follows: modules: [ '@nuxtjs/axios', ], And in my component, it's set up like this: <tem ...

I am unable to load any HTML files in my VueJS iframe, except for the index.html located in the public

Within the template of my vue component, I am utilizing the following code: <iframe width="1000vw" height="600vh" src="../../public/myHtmlFile.html"></iframe> Unfortunately, the file specified in the src attribut ...

"Exciting Changes in Color According to the Active State of vue-route-link

I am trying to find a way to customize the CSS based on whether a link is exact or active. Essentially, when a user clicks on a menu item, I want the underline to change depending on whether the link is an active router-link. Although I was able to accompl ...

Find the differences between the values in two arrays of objects and eliminate them from the first array

const arrayOne = [ { id: 22, value: 'hello' }, { id: 33, value: 'there' }, { id: 44, value: 'apple' } ]; const arrayTwo = [ { id: 55, value: 'world' }, { id: 66, value: 'banana' }, ...

ruby use JSON library to import data

How can I utilize the parsed information from the data.rb file within the main.rb file? I am attempting to determine the frequency of the years "2017" and "2014". I aim to send back both counts to the count_years method found in main.rb. What is the corr ...

Resize the Excel DNA array to return vertically

I am experimenting with creating dynamic arrays using the Excel-DNA API. While I have managed to generate the desired output, I am looking to format it vertically. Below is the C# code for my User Defined Function (UDF). I referred to this link as a guide ...

Issue with autoplay slideshow functionality not activating when opened in a new tab

The owl.carousel.js plugin is used for creating a jQuery slideshow. Initially, the slideshow works correctly, but I noticed that the autoplay feature stops working when I open a new tab in Firefox or Chrome. Demo : Demo : $(document).ready(function () ...

Various behaviors in multiple instances of DatePicker

Currently, I have a form with two datePicker elements (using jQuery UI). When I hover over a date in the first datePicker, an AJAX call is made successfully. However, the issue is that the AJAX call is triggered for both datePickers when I only want it to ...

Initializing a primitive array may interfere with the functionality of other arrays

Currently, in my Xcode project, I am utilizing primitive array types. For instance: int matrix [10][10]; Moreover, I am implementing a basic loop for initializing the array for(int x=0;x<=10;x++) for(int y=0;y<=1;0y++) matrix[x][y] = 0; I ...

Mysterious behavior in JavaScript causes it to skip the second index of an array

Below is a lengthy snippet of html code that I would like to discuss: <!DOCTYPE html> <html> <head> <script type = "text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script> <script> $( ...

Button-click scrolling is our featured feature!

One interesting feature on my website is a button (within a div-element) located in the bottom-right corner. I am now looking to enhance this by adding a jQuery function that enables the user to scroll down the page incrementally simply by clicking and hol ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

Custom Typescript type that runs concurrently with the base type is disregarded

Assumption: When creating a custom type that mirrors an existing type, the expectation is for variables assigned to that type to maintain it and not default back to the base type. In the function f provided below, the expected return type should be Dog ins ...