Home > OS >  How do I sort some HTML elements alphabetically?
How do I sort some HTML elements alphabetically?

Time:07-09

function render() {
  let lastContact = listadeContatos.slice(-1);
  boxapp__contact.innerHTML  = lastContact
    .map((contact) => {
return `<div  id=${
        contact.id
      } onclick="boxapp(this.id)">
        <div >${contact.fistName[0].toUpperCase()}</div>
        <div >${contact.fistName}</div>
      </div>`;
    }).join("");
  const contacts = document.querySelector(".box-app__contacts-list");
  const c = [...document.querySelectorAll(".contact__name")];
  if (listadeContatos.length > 1) {
    c.sort((a, b) => (a.innerText > b.innerText ? 1 : -1)).forEach((node) => {
      contacts.appendChild(node);
    });
  }
}

I made a simple app, a list of contacts, and I wanted them to be sorted alphabetically when a new contact is added and called for rendering, but nothing I've tried has worked. And the similar issues I encountered were not enough for me to find the way to a solution. I'm still learning Javascript. I would like someone to help me if they can. And sorry if there are any spelling mistakes. I'm using Google Translate to make this post.

CodePudding user response:

Try using this sort function: c.sort((a, b) => (a.innerText < b.innerText? -1 : a.innerText > b.innerText? 1 : 0))

CodePudding user response:

simply sonething like that... :

function render()
  {
  let lastContact = listadeContatos.slice(-1);
  
  boxapp__contact.innerHTML  = lastContact
    .map( contact => 
      ( { key : contact.fistName
        , inHTML : `
        <div  id=${contact.id} onclick="boxapp(this.id)">
          <div >${contact.fistName[0].toUpperCase()}</div>
          <div >${contact.fistName}</div>
        </div>`}))
    .sort( (a,b) => a.key.localeCompare(b.key) )
    .reduce(( rHTMP, {inHTML}) => rHTMP   inHTML, '')
    ;
  }
  • Related