Arranging an array of JavaScript objects by their element names

Currently, I am working on writing a validation script using JavaScript and prototype.

The main idea behind this task is to iterate through all the elements of a form and validate each answer. While my code is functional, there is an issue with the array of DOM elements being unsorted. Ideally, I would like to sort the elements based on their ID.

Below is the snippet of my code. It works perfectly unless I comment out elem.sort(zelementsort);

function zelementsort(a,b) {
    if (a.name > b.name)
        return -1;
    else if (b.name > a.name)
        return 1;
    else 
        return 0;
}   

var elem = document.getElementById('myform').elements;
elem.sort(zelementsort);

for(var i = 0; i < elem.length; i++)
{
     alert("Name = " + elem[i].name);

}

I suspect that some elements might not have names, causing potential issues. Does anyone know of a simpler way to sort an array of DOM elements by their .name attribute?

Answer â„–1

Here's the solution to accomplish that:

$$('#myForm *[name]').sortBy(function(element){ return element.name; });

Answer â„–2

The reason for this is that the sort() method is not part of the DomElementList obtained from .elements.

An interesting workaround is to utilize the Array.sort method on your DomElementList using a clever Javascript trick.

Subsequently, you can reinsert the nodes into the DOM without duplicating them, simply moving their positions.

var myform = document.getElementById('myform'),
    elem = myform.elements;

// implement Array.sort() on our DomElementList
Array.prototype.sort.call(elem, function()
{
    if (a.name > b.name)
        return -1;
    else if (b.name > a.name)
        return 1;
    else 
        return 0;
});

for(var i = 0; i < elem.length; i++)
{
     myform.appendChild(elem[i]);
}

Answer â„–3

Utilizing a native JavaScript sort function to implement sorting logic without the use of conditional statements like if.

elements.sort(function(a, b) { return 2 * (a.name > b.name) - 1; })

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

Determine the data type of a property within a JavaScript object

I am currently working with a javascript object that looks like this: venue = { id: 0, name: '', venueimage_set: [ { imageurl: '', }, ]... At a later point in my code, I need to modify the object ...

Utilizing Google Maps to display an infowindow upon clicking a location from a geojson file

I want to implement info windows that pop up when markers on a map are clicked. I used the sample code provided by Google (below) to create a marker map from geojson files dragged and dropped into the window. My goal is for the info windows to show text ta ...

React Components Changing Route Leads to Empty Display

My current challenge involves setting up dynamic routing in my application to enable the viewing of products from different stores. Essentially, I am developing an app where users can add stores and browse through their items. I have implemented a dynamic ...

What is the best way to import information from a CSV or Excel file directly into my program?

I am currently using puppeteer for automating a form submission process. I am looking to extract data directly from a csv file and input it into the form. Can someone guide me on how to achieve this? The CSV file contains the following information: Fir ...

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...

Ways to determine if the navigation bar is in a collapsed state or not

I am working with a navbar: <nav id="navbar" class="navbar fixed-top navbar-expand-md navbar-light bg-light"> <a class="navbar-brand" href="#"></a> <button id="toggle" class="n ...

Confirm that only the days of the present month are eligible for selection

I have been given the responsibility of validating a date field that is populated when an invoice is created. The date field consists of a text box and three button objects allowing users to select a date from a calendar, input today's date, or remove ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

Unable to alter the vertex color in three.js PointCloud

I'm currently facing an issue with changing the color of a vertex on a mouse click using three.js and Angular. After doing some research, I believe that setting up vertex colors is the way to go. My approach involves setting up vertex colors and then ...

What could be the reason the forEachRow function is not impacting the second or subsequent pages within the dhtmlx grid?

I'm trying to format the grid rows as they load. My goal is to have the row appear in red with some conditions. It works correctly for the first page, but not for subsequent pages of the grid. Below is my detailed code. If anyone knows why this is hap ...

Using Selenium Webdriver to set a cookie with a Chrome extension

I have been experimenting with a Chrome extension in order to set a cookie when I use a Selenium Webdriver instance to open a page. Despite trying various methods suggested on different Stack Overflow posts, none of them seem to work as the cookie does not ...

Utilizing various lodash filters in React for enhanced data manipulation

In my code, there is a function that filters a large set of objects based on specified inputs. The code snippet for this filtering function looks like this: filterLocations(filters) { let filteredLocations = _.filter( this.state.locations, locat ...

JavaScript makes it easy to streamline conditions

Can someone help me simplify this repetitive condition? if (this.get('fileUrl')) { const isUnsplash = this.get('fileContainer.asset_kind') === 'UnsplashAsset'; return Asset.create({ url: this.get('f ...

Utilize data from API responses to configure settings in angular-datepicker using pickadate.js

I am attempting to configure the options for the angular-datepicker, which is utilizing pickadate, by fetching data from a web-api call. Here is my current code: <label for="datepicker">Date:</label> <input type="text" id="datepicker" pick ...

What causes the z-index value to stay the same even after it has been modified using the .css() function?

The z-index property defaults to auto, as explained in the MDN documentation. Despite setting the z-index to 1 using the following code: $("body").css("z-index", 1); Upon retrieving the value of z-index with this code: $("body").css("z-index"); The re ...

Guide to making a jQuery counter

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="../plugin/jquery-1.6.1.min.js"></script> ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Define a property within an object literal that sets a function's property

I am defining a new tasks object: var tasks = { test: () => { /// .... } }; Within the test function, I am attempting to assign a value to the tasks.test.description property. Despite my efforts, such as: var tasks = { test: () ...

What is the best way to detect the window scroll event within a VueJS component?

Looking to capture the window scroll event in my Vue component. This is what I have attempted so far: <my-component v-on:scroll="scrollFunction"> ... </my-component> I have defined the scrollFunction(event) in my component methods, but it ...

What is the best way to identify the contrasts between two arrays?

I have two arrays: $valid_sku_array $qb_sku_array I need to find the common elements between them using the intersect function, and then display the elements that are different. First, I perform the operation sensitive to case: // Case Sensit ...