Explanation of Sorting Numbers in JavaScript Code

I'm currently reviewing the descending number sorting code below and I'm feeling a bit confused:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

In the given code, the return value will be (b-a), for example, 100 - 40 = 60. However, there is no 60 in the array provided.

Answer №1

Sorting Implementation from Mozilla -

  1. If compareFunction(a, b) results in a value less than 0, then sort a to a lower index than b, placing a first.

  2. If compareFunction(a, b) returns 0, maintain the position of a and b relative to each other but ensure they are sorted with respect to all other elements. Note: Some browsers may not follow this behavior due to ECMAscript standards.

  3. If compareFunction(a, b) yields a value greater than 0, then sort b to a lower index than a, making b come first.
  4. The compareFunction(a, b) must consistently return the same value when provided with a specific pair of elements a and b as arguments. Inconsistent results will lead to undefined sort order.

You can observe the functionality of the function by adding logging statements.

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){
console.log("a = " + a + 
        ": b= " + b + 
        ": b - a = " + (b - a) + 
        " swap a and b if b-a > 0");
return b - a});

Output -

a = 40: b= 100: b - a = 60 swap a and b if b-a > 0 
a = 40: b= 1: b - a = -39 swap a and b if b-a > 0 
a = 1: b= 5: b - a = 4 swap a and b if b-a > 0 
a = 40: b= 5: b - a = -35 swap a and b if b-a > 0 
a = 1: b= 25: b - a = 24 swap a and b if b-a > 0 
a = 5: b= 25: b - a = 20 swap a and b if b-a > 0 
a = 40: b= 25: b - a = -15 swap a and b if b-a > 0 
a = 1: b= 10: b - a = 9 swap a and b if b-a > 0 
a = 5: b= 10: b - a = 5 swap a and b if b-a > 0 
a = 25: b= 10: b - a = -15 swap a and b if b-a > 0

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

Securely Connecting to an MQTT Broker with a JavaScript Client (React) while Safeguarding Credentials

Looking to securely connect my React application to a Mosquitto MQTT broker without exposing sensitive credentials to users who can access the JavaScript code. Considering options for authentication, such as using an API with JWT authentication to retriev ...

Obtain the latest NPM package versions

I am currently seeking a way to compile a comprehensive list of all major versions that have been released for a specific NPM package. By utilizing the following API link, I can retrieve a list of available versions which includes both the major and exper ...

What is the process for assigning a random string value to each document within a mongodb collection using the mongo shell?

Looking to assign a randomly generated string property to every item in a MongoDB collection. Planning to leverage the mongo shell and the updateMany function for a swift and efficient solution. ...

Conflict in the naming and scoping of IE7 and IE8

While reviewing some code, I encountered a problem in Internet Explorer 7 and 8. Despite the constructor executing properly when stepped through, upon returning I received an error stating "Object does not support this property or method." How frustrating! ...

Updating a boolean array post email dispatch in C#

After sending an email, I am looking to update a boolean value in an array to indicate that the email has been sent for that specific Sensor ID. To maintain security, I have removed sensitive information such as my email address and password from the code ...

Is there a way to implement the focus function and invoke a JavaScript function within an ASP.NET application?

Whenever I click on the textbox, a function is called. The code for that is: onclick="GetColorBack()" However, the GetColorBack function is only called when clicking on the textbox. If I navigate using the TAB key, it does not trigger the function. Is t ...

Creating a spherical shape using random particles in three.js

Can anyone assist me in creating a random sphere using particles in three.js? I can create different shapes with particles, but I'm unsure how to generate them randomly. Here's my current code: // point cloud geometry var geometry = new THREE. ...

Conceal any null and empty values in the output textarea

I am currently working on an HTML form where users input information using <input> and <select> fields. After entering the required data, they submit the form and it is displayed in a <textarea> with basic formatting. To see an example, ...

The element does not have a property named 'className' in the object type '{ props: ReactNode; }'

I am currently in the process of converting a Next.js project from JavaScript to TypeScript, and I encountered an issue: Property 'className' does not exist on type '{ props: ReactNode; }'. In JavaScript, I could access className from p ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

What is the best way to define these variables at a global scope within my controller?

In my controller (NodeJS/Express), I have 10 routes that all use the same variables 'startDate' and 'endDate'. Is there a way to declare these globally so they don't need to be repeated in each route? Currently, my code checks if ...

Tips on how to showcase JSON data retrieved from a RESTful API using JavaScript or jQuery

Is there a way to avoid repeating myself when displaying all content from my data array, like in the example below? // Program guide Rest $(document).ready(function() { $.ajax({ cache: false, url: "http://engrid2media.com/nextt/api/epg/s ...

Troubleshooting problem with $http in AngularJS: encountering challenges with HTTP JSONP requests

I encountered the following error message while attempting to utilize the JSONP method in AngularJS: Uncaught SyntaxError: Unexpected token : http://example.com/getSomeJson?format=jsonp&json_callback=angular.callbacks._0 Could someone please ass ...

Hooray - Locate and display all attributes that correspond to the search criteria

Suppose I have some HTML code like this: <a class="my-lovely-name" title="hello" href="fb.com">Random stuff</a> <div class="my-lovel-name" title="ew" href="yb.com">blabla</div> I want to figure out how to extract all the values of ...

Changing the background-color with CSS class toggling

I'm having an issue with an element that is supposed to change its background color from "lightGreen" to "red" upon hovering. However, even though the class is being added properly, the color remains lightGreen. It's worth noting that the elemen ...

Error alert: Index not defined!

I have a dropdown select that needs to be populated with values from a database. I then need to validate the selected value using a JavaScript function, which is already implemented. The dropdown list has two columns: one for ID identifiers and another fo ...

Is it possible to remove a specific directory from the webpack build configuration in a vue-cli-3 setup?

After spending 3 hours adding the line: exclude: ['./src/assets/sass'] in 20 different places, I am seeking guidance on where it should actually be placed. Below is my current setup for the css-loader (util.js): 'use strict' const path ...

Saving the Chosen Option from Button Group into react-hook-form State

Struggling to save the chosen value from MUI Button Group into react-hook-form's state, but encountering challenges with the update not happening correctly. view codesandbox example Below is a simplified version of my code: import { ButtonGroup, But ...

`store and utilize the data retrieved from chrome.sync.storage.get()`

As I work on a Chrome extension, I am facing an issue with retrieving information from chrome.storage. This involves saving some data in the options page and then accessing it in the content_script. In the options.js, this is how the information is saved: ...

Modify object rotation animation direction using keyboard controls in Three.js

Adjusting the object rotation direction with key controls is within my capability by utilizing the following code: case 37: scene.rotation.x -= 0.01; break case 38: scene.rotation.z -= 0.01 break Nevertheless, the rotation remai ...