Anomalous sorting methods found in JavaScript arrays

While attempting to sort a JavaScript array, I came across an unexpected behavior.

var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k'];

arr.sort(function (a, b) {
  console.log(a, b);
  if (a.length < b.length) return 1;
  else if (a.length > b.length) return -1;
  else return 0;
});

Everything works perfectly in this scenario and returns the same array.

The console output looks like this:

https://i.sstatic.net/b40hn.png

However, when I try sorting with the following input,

var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k', 'l'];

The result is different:

https://i.sstatic.net/w6C2A.png

I am puzzled by this inconsistency and unable to determine the cause of it.

For your information, I implemented this custom sorting logic to arrange elements based on their length.

Answer №1

When it comes to sorting algorithms in ECMAScript, there is no specific algorithm mandated. The stability of the sorting algorithms is also not expected (Array.prototype.sort). Stability in sorting algorithms refers to maintaining the relative order of elements that are deemed "the same". Two items are considered the same when the comparison function returns 0 during Array#sort. While InsertionSort and MergeSort (used by Apple and Mozilla) are stable, QuickSort (utilized by Google Chrome) is not due to Issue 90. In scenarios where an array contains 10 or fewer elements, Chrome resorts to using InsertionSort. Safari and Firefox will sort an array like ["sed", "dolor", "ipsum", "foo", "bar", "cat", "sit", "man", "lorem", "amet", "maecennas"] based on character length, ensuring that "sed" retains its initial position. However, Chrome may prioritize "cat" for the first position. It seems Chrome developers have a soft spot for kittens...

If you feel the need to ensure stability in your sorting, consider implementing a stable algorithm like MergeSort yourself.

For more details, visit the full post here

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

Framer Motion's AnimatePresence feature fails to trigger animations when switching between pages

I'm running into issues with the Framer Motion library, specifically with the AnimatePresence transition. I've managed to make it work in normal situations, but when I encapsulate my Routes within a custom implementation, the exit animation fails ...

Synchronizing Data between Elasticsearch and MongoDB to Retrieve Query Results

I'm currently working on a project that involves integrating Elasticsearch with our existing Mongo data source. The team has decided not to use river due to lack of support, and instead, they plan on running a cron job to update all the records in Ela ...

A guide to quickly obtaining the width and height of an element as it resizes in Vue.js

Is there a way to immediately get the width and height of an element when it is resizing in Vue.js? I have created a Codepen illustration and would appreciate any help in making it function correctly, thank you! Codepen let app = new Vue({ el: &apos ...

Using a for loop in JavaScript to dynamically display TextBoxFor(model=> model[i].prop) in an MVC application

I need some help getting this code to function correctly: $('#ddl').change(function () { $('#cont').html(''); var count = getCount($('#ddl').val()) for (var i = 0; i < count ; ...

Ways to Utilize Class Arrays

I have multiple classes containing numerous methods and functions that typically handle mx1 arrays. Specifically for a given class: S1.x=randn(m,1); S1+2*randn(m,1); % Plus Override S1.smooth; % Class Methods S1.detrend; Now, I want to manage class array ...

Utilize JavaScript code from an npm package to incorporate its functionality within your program

I have recently integrated the htmlhint library into my development workflow. I am able to execute it via the command line on any HTML file using the following command: npx htmlhint src/test-file.html Upon running this command, the file is linted and any ...

Transferring data from a JavaScript variable to PHP using AJAX

I’m currently working through the tutorial at http://www.w3schools.com/php/php_ajax_database.asp and I think I have a good grasp of how it all operates. This is my code: PHP: <?php include('./db.php'); $PM = mysqli_query($con, "SELECT DIS ...

Display a variety of images using ng-grid in angular js

I have integrated ng-grid into my Angular application and I am looking to display different images in the ng-grid based on certain conditions or row index. Below is the HTML code snippet: <html ng-app="myApp"> <head lang="en"> <meta ...

Request body for deleting data using Angular's $http service

Below is the code snippet: params = method: 'DELETE' url: "profiles/#{@currentProfile.id}/boxes/#{@box.id}/messages" data: ids: ids headers: "Content-Type": "application/json;charset=utf-8" $http(params) After executing this DE ...

JavaScript and Angular are used to define class level variables

Hello, I'm currently diving into Angular and have encountered an issue with a class level variable called moratoriumID in my component. I have a method that makes a POST request and assigns the returned number to moratoriumID. Everything seems to work ...

Repetitive firing of events implemented using AngularJS

Hello, I'm currently trying to trigger an event repeatedly in AngularJS. Below is the code snippet: Here is the HTML code: <li ng-repeat="y in names | limitTo: 6" repeat-done="ratingwithng()"> <a href="<?php echo $this->config-> ...

Vue.js: Efficiently handling multiple buttons within a Dropdown menu

I am currently working on a Vue.js Project and have a Dropdown component. Here is the code snippet: <template> <v-menu close-on-click transition="slide-y-transition"> <template v-slot:activator="{ on, attrs }" ...

Enhance the functionality of the button by implementing AJAX with the use of data

I am currently working on implementing an update function without using forms. Instead, I am utilizing data-* attributes and ajax. My goal is to prevent the button from triggering after updating the values. However, I am facing an issue with my script as ...

Vue Eslint Extension

My current project utilizes the eslint vue plugin with specific rules set in place. "rules": { "vue/html-closing-bracket-newline": ["error", { "singleline": "never", "multiline": "always" }], "vue/html-closi ...

Ways to access dropdown menu without causing header to move using jQuery

Greetings everyone, I am currently working on a dropdown language selection feature for my website. The issue I am facing is that when I click on the language dropdown in the header, it causes the height of the header to shift. $('.language- ...

Utilizing modal functionality for seamless integration of new data into mui-datatable

When trying to add a new data entry using a modal box, I encountered an issue where the new data was not being added to the datatable. Is there a solution for this problem? Below is the code snippet I used: let id = 0; function createData(name, provider) ...

What is the rationale behind angular-fullstack's decision to implement both put and patch requests in Express?

I recently stumbled upon an article discussing the distinctions between PUT and PATCH requests (Difference between put and patch). Though I've gained some clarity on the topic, there are still aspects that remain unclear to me. One of my major querie ...

Does the default input default to text format?

I have a somewhat peculiar question. I'm currently experimenting with Javascript for a plugin and came across an interesting scenario. Let's say I have an input element that is structured like this: <input type='cc' id='cc&apo ...

My goal is to develop a custom forEach function that retrieves a substring from each element in an array

I have a file containing image names like: sciFi.png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, loft.png, basement.png, avenger.png, friend.png In my JavaScript document, I am trying to read this file and convert it into an array. Then, I w ...

I am facing an issue where the data is not being populated in my form even though I am using ng

Here is a form with grouped inputs using the ngModelGroup directive: <form #form="ngForm" (ngSubmit)="submit(form.value)"> <fieldset ngModelGroup="user"> <div> <label>Firstname:</label> < ...