Skip to content Skip to sidebar Skip to footer

How To Sort Javascript Object Array By Element.name

I am try to write some validation script using javascript and prototype. What I want to do is to loop through all the elements of a form and validate each answer. My code works, B

Solution 1:

This should do it:

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

Solution 2:

This is because sort() is not a method of the DomElementList you retrieve with .elements.

The nice thing is that you can apply the Array.sort method to your DomElementList using a Javascript trick.

Then, you just have to append the nodes again in the DOM, they won't be duplicated but moved.

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

// call the Array.sort() method on our DomElementListArray.prototype.sort.call(elem, function()
{
    if (a.name > b.name)
        return -1;
    elseif (b.name > a.name)
        return1;
    elsereturn0;
});

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

Solution 3:

Implementation without if based on native js sort function.

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

Post a Comment for "How To Sort Javascript Object Array By Element.name"