Home > Mobile >  How can I sort an unordered list by the list items' ids with vanilla JavaScript?
How can I sort an unordered list by the list items' ids with vanilla JavaScript?

Time:12-07

I have a list of meeting days, e.g. Monday morning, Monday afternoon, Monday evening, Tuesday morning and so on which are then displayed on a website's front end as an unordered list. Because the text is not alphabetical I want to sort the items using IDs I have created for each based on their item aliases with an added prefix. E.g. the "monday-morning" alias is now "aa-monday-morning" and that in turn is used to create id="aa-monday-morning" Each of the list items has the class "sort" and sits in a ul with the id "meetings". [I do realise that if they'd been set up in the correct order in the first place, I wouldn't have a problem, but it's too late, now as there are 100 items tagged with those list items].

I understand that I need to select all the items with the class name "sort" and then convert them to an array before sorting them by their ids, but I am really struggling.

I started with some code I copied from somewhere but it doesn't seem to do anything and I'm not sure why.

let List = document.getElementById("meetings");
let listItems = List.getElementsByClassName('sort');
    sortList = Array.prototype.slice.call(listItems);
    if(listItems && listItems.length){
        listItems.sort(sortList);
        while (List.hasChildNodes()) {
            List.removeChild(List.lastChild);
        }
        while(listItems.length){
            var newList = listItems.shift();
            List.appendChild(newList);
        }
    }
function sortList(a, b){
    var aid = (a.id);
    var bid = (b.id);
    return aid - bid;
}
<ul id="meetings" >
<li id="aa-monday-morning" >Monday morning</li>
<li id="ba-tuesday-morning" >Tuesday morning</li>
<li id="bc-tuesday-evening" >Tuesday evening</li>
<li id="cc-wednesday-evening" >Wednesday evening</li>
<li id="dc-thursday-evening" >Thursday evening</li>
<li id="fb-friday-afternoon" >Friday afternoon</li>
<li id="ca-wednesday-morning" >Wednesday morning</li>
<li id="bb-tuesday-afternoon" >Tuesday afternoon</li>
<li id="cb-wednesday-afternoon" >Wednesday afternoon</li>
<li id="ac-monday-evening" >Monday evening</li>
<li id="ab-monday-afternoon" >Monday afternoon</li>
</ul>

The end result should be:

    <ul id="meetings" >
    <li id="aa-monday-morning" >Monday morning</li>
    <li id="ab-monday-afternoon" >Monday afternoon</li>
    <li id="ac-monday-evening" >Monday evening</li>
    <li id="ba-tuesday-morning" >Tuesday morning</li>
    <li id="bb-tuesday-afternoon" >Tuesday afternoon</li>
    <li id="bc-tuesday-evening" >Tuesday evening</li>
    <li id="ca-wednesday-morning" >Wednesday morning</li>
    <li id="cb-wednesday-afternoon" >Wednesday afternoon</li>
    <li id="cc-wednesday-evening" >Wednesday evening</li>
    <li id="dc-thursday-evening" >Thursday evening</li>
    <li id="fb-friday-afternoon" >Friday afternoon</li>
    </ul>

Thank you for reading.

CodePudding user response:

You can create a variable for the parent element of the list items listElement and another that holds an array of the list items listItemElements.

Sort the array according to your criteria: read about the compare callback function argument that is provided to array.sort().

Finally, (re-)insert the list item elements into the parent element in the new, sorted order.

Here's a complete code example:

const listElement = document.getElementById('meetings');

const listItemElements = [...listElement.querySelectorAll(':scope > li.sort')];

listItemElements.sort(({id: a}, {id: b}) => a < b ? -1 : a > b ? 1 : 0);

for (const li of listItemElements) listElement.appendChild(li);
<ul id="meetings" >
<li id="aa-monday-morning" >Monday morning</li>
<li id="ba-tuesday-morning" >Tuesday morning</li>
<li id="bc-tuesday-evening" >Tuesday evening</li>
<li id="cc-wednesday-evening" >Wednesday evening</li>
<li id="dc-thursday-evening" >Thursday evening</li>
<li id="fb-friday-afternoon" >Friday afternoon</li>
<li id="ca-wednesday-morning" >Wednesday morning</li>
<li id="bb-tuesday-afternoon" >Tuesday afternoon</li>
<li id="cb-wednesday-afternoon" >Wednesday afternoon</li>
<li id="ac-monday-evening" >Monday evening</li>
<li id="ab-monday-afternoon" >Monday afternoon</li>
</ul>

CodePudding user response:

You can use the following approach:

```
function sortById(){
  const result=document.getElementsByClassName("sort");
  let arr=[];
  for(const item of result){
       arr.push(item.id)
  }

  let sortedArr=arr.sort((a,b)=>a>b);
  return sortedArr;
}
```
  • Related