I find the "sort function" confusing and difficult to grasp

This question might seem easy for some, but I am new to JavaScript.

I'm having trouble understanding this part of the function:

kids.sort(function(n, m)

What does n and m represent? How can I grasp these types of functions?

Thanks!

<script>
function sortkids(e) {
     if (typeof e == "string") e = document.getElementById(e);
     var kids = [];
     for(var x = e.firstChild; x != null; x = x.nextSibling)
         if (x.nodeType == 1) kids.push(x);
     kids.sort(function(n, m) { 
                   var s = n.firstChild.data; 
                   var t = m.firstChild.data;
                   if (s < t) return -1;    
                   else if (s > t) return 1;  
                   else return 0;           
               });

     for(var i = 0; i < kids.length; i++) e.appendChild(kids[i]);
}
</script>
<ul id="list"> 
<li>one<li>two<li>three<li>four <!-- items are not in alphabetical order -->
</ul>
<button onclick="sortkids('list')">Sort list</button>

Answer №1

.sort function in JavaScript is responsible for sorting items inside an array. To specify how you want the items sorted, you need to provide a comparison function that determines which item should come first. This function takes two parameters and returns -1 if the first element is smaller, 0 if they are equal, and 1 if the first element is larger.

When you use .sort, it compares pairs of elements by asking your function which one should precede the other. It repeats this process until the entire array is properly sorted.

Answer №2

x and y will represent different elements from an array. By repeatedly calling the function with various array elements, it should return a value indicating whether x is equal to, less than, or greater than y. This allows the sort function to sort the array effectively, without requiring knowledge of the elements themselves. The necessary information is provided by the function passed into it.

The code snippet organizes DOM elements within an array and sorts them accordingly; however, this does not affect their order in the actual DOM structure. The subsequent steps involving e.appendChild ensure that the sorted array's elements are correctly positioned in the DOM. This method works due to the behavior of the appendChild function, which relocates an element if it already exists in the DOM, and always appends new elements at the end.

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

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Azure SQL Server linked with a REST API built on Express.js/Node.js encountered an error stating: "TypeError: req.sql is not a function"

Having trouble connecting to Azure SQL Server with express4-tedious. I'm working on building an app in react-native with a Node/Express server (REST API), but encountered this error after setting up express4-tedios in Express: req.sql is not a functio ...

A more concise method to verify if something is undefined in JavaScript

Anyone have suggestions for a more concise idiom to use? const x = module || window; // Reference Error fallback Is there a shorter method to verify the presence of module? ...

Unable to substitute a value using the useState hook in React

Whenever I click a key, I attempt to update the value of a variable but it appears not to be working as intended. ↓ The current implementation is not effective and needs improvement import React, { useState, useEffect } from 'react'; const Li ...

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

Utilize Django to leverage a JSON file stored within a context variable for use in jQuery

I need to utilize a list in Jquery and integrate it with the Autocomplete jQueryUI widget. The list is small, so creating a new request seems unnecessary. Therefore, I believe using Jsquery's getJSON is also not required. Here is my current setup: ...

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

Troubleshooting tip for React JS: encountered an unexpected object error when trying to import components

I've been working on building a react app with Create React App, and everything was going smoothly until I encountered a frustrating error message: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Angular CORS problem when sending information to Google Forms

When submitting the data: Error Message: Unfortunately, an error occurred while trying to send the data. The XMLHttpRequest cannot load https://docs.google.com/forms/d/xxxxxxxxxxxxx/formResponse. The response to the preflight request did not pass the ac ...

What is the best way to set the focus on a Vue flat-pickr component?

Having trouble setting focus to the Vue flat-pickr component. Here's an example: <flat-pickr v-model="date_opened" id="file_opened" :config="flatpickr_config_date" :disabled="disableFileInfo&q ...

Can you assist me with setting a value in an ASP dropdownlist?

I have an asp dropdownlist and I need to set its value from the client side. Although I am able to retrieve the data from the client side, I am facing difficulty in setting it in my asp dropdownlist using JavaScript. HTML <div class="col-md-6 form-gro ...

How can a list of objects in a JPA entity with a many-to-one relation to a data entity be sorted based on the result of a method call from the data entity?

In my JPA entity User, there is a OneToMany relation to a UserStats entity. I made changes to the code to use UserStats instead of storing victoryRatio directly in the User entity. Now, calculateVictoryRatio() method is implemented in the UserDetails entit ...

Utilizing AngularJs to differentiate between arrays and strings within an HTML template

I'm currently facing a challenge with creating a dynamic HTML template. In order to present data in a table, I need to distinguish between a regular String and an Array. Firstly, the HTML template is embedded within another template using the data-ng- ...

The problem stemming from the implementation of the useNavigate() Hook in a personalized React-Admin application

I've encountered a complex issue in my React-Admin application. Whenever I attempt to utilize the useNavigate() hook within my custom login component (MyLoginPage), an error message pops up: [Route] is not a <Route> component. All component chi ...

Generate a Report in Embedded Mode using the PowerBI API

Attempting to generate a new report using data from an embedded view, but encountering continuous "This content isn't available" messages and receiving a 403 error from the reportEmbed.min.js during rendering. While able to create and save reports suc ...

Customizing Angular 2's Webpack environment setup dynamically

Currently, I have set up Webpack to compile my Angular project. Within my project, there is an important file called env.js: module.exports.ENV = { API_URL: "http://localhost:5001/", ... }; In the webpack.common.js file, I am referencing this file l ...

Ensuring User Input Integrity with JavaScript Prompt Validation

I need help with validating input from a Javascript prompt() in an external js file using HTML code. I know how to call the Javascript function and write the validation logic, but I'm unsure how to handle the prompt and user input in HTML. Do I need ...

Tips on causing JavaScript execution to halt until an element has finished rendering

test.view.js timeDBox = new sap.ui.commons.DropdownBox({layoutData: new sap.ui.layout.GridData({linebreak: true}), change: function(oEvent){ oController.getKeyEqChart(); }, }), new sap ...

What is the best way to load data that is essential for the entire functionality of an AngularJs Application?

Within my application, there exists essential data that is utilized by various controllers to carry out their functions. For instance, the user and other entities must make REST calls to the server. Currently, I have an AppController (app.js) responsible ...