javascript sorting function that sorts when it's not supposed to

function longest(arr) {
  return arr.sort( (a,b) => {
    return a.length - b.length;
  });
}
var res = longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k','l']);
console.log(res); // -> [ 'f', 'a', 'c', 'd', 'e', 'b', 'g', 'h', 'i', 'k', 'l' ]

Isn't it strange how the function's return is sorting the array in this unexpected way? I thought it was supposed to keep the original order.

Is my understanding correct?

Answer №1

When using Array.protoype.sort, it's important to note that stability is not guaranteed, meaning equal elements may not always retain their original order.

The sort() method rearranges the elements within an array and returns the modified array. It's crucial to understand that this sorting process may not maintain stability, with the default sort order being based on Unicode code points for strings.

For more information about Array.sort(), visit this link.

Answer №2

One way to implement default sorting is by using the position of the item in the original array as a reference point. To improve performance, consider utilizing Sorting with map.

function sortWithOriginal(arr) {
    var copy = arr.slice();
    return arr.sort(function (a, b) {
        return a.length - b.length || copy.indexOf(a) - copy.indexOf(b);
    });
}
var result = sortWithOriginal(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l']);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Answer №3

When sorting in ascending order, the comparator function should utilize a - b instead of a.length - b.length. This is because a.length - b.length will always result in zero when dealing with single-letter alphabets. For example, when comparing ['ab', 'a'], it will return ['a', 'ab'] due to the shorter length of the first element in the array compared to the second.

function longest(arr) {
  return arr.sort( (a,b) => {
    return a - b;
  });
}

Answer №4

According to the information provided here:

If compareFunction(a, b) returns 0, a and b remain unchanged in relation to each other but are sorted amongst all other elements. It's important to note that not all browsers (e.g. certain versions of Mozilla from 2003 onwards) follow this specific behavior as guaranteed by the ECMAscript standard.

Considering that the compare function in your case always returns 0, and based on the insights shared in this discussion, it becomes apparent that different browsers handle element iteration differently. As a result, the outcomes can vary depending on the browser being used.

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

Enlarging an image on canvas and creating a repeating pattern

My canvas size is 500px x 500px. I have a png image that matches the canvas size, which you can view here. I am looking to resize the image to 100px x 100px and then use it as part of a repeat pattern on the canvas. This is how I achieve this: // First d ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...

Querying Mongoose Nested Data in Express: A Comprehensive Guide

I need to retrieve the "stocked" boolean value for item "4" belonging to user "456" from my mongoose data collection. However, when I try to query for this specific information, I end up receiving the entire user object instead. Data: data = [{ use ...

Choosing the current date and time (+15 minutes) from a date picker in Selenium:

I am facing difficulty in selecting today's date and the current time plus 15 minutes from the date picker using Selenium. The code I have written for the date selection is not working. Here is the code snippet: DateFormat dateFormat2 = new SimpleD ...

Exploring the Power of React's Ref API

Currently, I am following tutorials on Udemy by Max where he discusses how to work with Ref Api's in React 16.3. In one of the lectures, he demonstrated creating a ref inside a container class, not App.js, using this.lastref = React.createRef();. He ...

Received an Error: (middle value)(...) does not function as intended [Yes, Formik]

const {values, handleChange, handleSubmit, errors} = useFormik({ initialValues: { name: '', address: '', latitude: '', longitude: '', nit: '', category: '', ...

Service running in the background in React Native

In the process of creating a React Native application, I am looking to retrieve data from the web every quarter of an hour. The method I choose should be capable of fetching data in the background while being compatible across multiple platforms. Is ther ...

What is the most effective method for adding data from an AJAX call?

Currently, I am utilizing JSON in conjunction with AJAX to dynamically generate all necessary DOM elements. However, I have been contemplating whether this approach is ideal. For instance, when creating a table of data, would it be more efficient to constr ...

Maximizing Efficiency on the Frontend: Balancing Requests with Caching

I am currently tackling a large website that has accumulated quite a bit of technical debt that needs to be addressed. The site contains a significant amount of JavaScript and CSS files being loaded. Currently, these files are aggregated and minified in la ...

React does not support the map function

I've been struggling for three days to figure out why I am unable to place multiple elements in an array. Interestingly, when I try to access only one element using this.state.dat.nombre or dat.carrera, it works perfectly fine. However, when I attempt ...

Change from one value to another using a decaying sinusoidal wave

Can someone help me come up with a formula that will smoothly transition from a starting value to an end value over a specified time using a Sin or Cos wave? I'm attempting to replicate a bouncing effect like the one shown in my sample using CSS and ...

resolve problems with Jquery scripts

Having some issues with importing a script from another file in jQuery. I have tried using $.getScript and $.ajax(); how can I incorporate a script like require.js in jQuery? util.js function getSessionInformation () { $.ajax({ url: '../contr ...

The setInterval function will run just one time when triggered by an onclick event

After watching a YouTube tutorial on creating desktop notifications, I had an idea to use it as a reminder tool. For example, having a specific reminder appear as a desktop notification every 30 minutes when triggered by clicking a button. However, the cod ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

What is the reason behind the browser permitting cross-origin POST requests but not PUT requests?

Let's consider a straightforward example of utilizing the XMLHttpRequest. The following code snippet functions correctly (you can verify in the network tab or by navigating your browser to http://requestb.in/yckncpyc) despite displaying a warning in ...

The initialization of the ng-model to an empty string as the default value

I am currently working on a user login and registration form where I noticed that the default values appearing are most likely cached by my browser. I am exploring ways to clear these values programmatically so that the input boxes are empty. Despite attem ...

What is the best way to refresh jCarousel following the loading of AJAX content?

After purchasing a custom jCarousel JavaScript (available at http://pastebin.com/BwsVpNjr), I encountered an issue when trying to load content with AJAX. The carousel breaks because it is unable to detect the width or height. Is there a way to have jCarous ...

Testing HTTP requests on a form click in Vue.js 2 - Let's see how

Within my component, I have the following method: methods:{ ContactUs(){ this.$http.post("/api/contact-us").then((res)=>{ ///do new stuff },(err)=>{ //do new stuff }) ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

What steps should I follow to incorporate channel logic into my WebSocket application, including setting up event bindings?

I'm currently tackling a major obstacle: my very own WebSocket server. The authentication and basic functionality are up and running smoothly, but I'm facing some challenges with the actual logic implementation. To address this, I've create ...