Sort JS Object array

Asked

Viewed 903 times

2

Speaks Guys, I started studying JS and created a list function that creates the list that checks the user’s gender and creates a list as below.

<ul>
     <li>Diego é homem e possui 23 anos</li>
     <li>Gabriela é mulher e possui 18 anos</li>
     <li>José é homem e possui 30 anos</li>
     <li>Maria é mulher e possui 27 anos</li>
</ul>

<button onClick="">Ordenar por nome</button>
<button onClick="">Ordenar por idade</button>

<button onClick="">Exibir apenas homens</button>
<button onClick="">Exibir apenas mulheres</button>
<button onClick="">Exibir todos</button>

The first two buttons should sort the list by name and age. The other 3 buttons should apply filters to the list showing only men, only women or all. The filter should work close to the ordering so it should be possible to filter only men and sort by age.

I already created the function to sort by age, I gave a console log and is ordering my question is how do I order only when you click the button

var users = [{
    nome: 'Diego',
    idade: 23,
    sexo: 'M',
  },
  {
    nome: 'Gabriela',
    idade: 18,
    sexo: 'F',
  },
  {
    nome: 'José',
    idade: 30,
    sexo: 'M',
  },
  {
    nome: 'Maria',
    idade: 27,
    sexo: 'F'
  },
  {
    nome: 'Amanda',
    idade: 26,
    sexo: 'F'
  }
];

function list() {
  // Cria a lista do elemento
  var listElement = document.createElement("ul");

  for (let value of users) {
    sexo = value.sexo;

    switch (sexo) {
      case "F":
        value.sexo = "Feminino";
        users = value.nome + " é " + value.sexo + " e possui " + value.idade + " anos."
        break;

      case "M":
        value.sexo = "Masculino";
        users = value.nome + " é " + value.sexo + " e possui " + value.idade + " anos."
        break;
    }

    //Cria a lista de item
    var itemElement = document.createElement('li');

    //Define seu conteudo
    itemElement.appendChild(document.createTextNode(users));

    //Adiciona um item a lista
    listElement.appendChild(itemElement);
  }

  return listElement;
}

function byAge(a, b) {
  return a.idade - b.idade;
}

//console.log(users.sort(byAge));

// Add the contents of options[0] to #foo:
document.querySelector('#app').appendChild(list(users));
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div id="app"></div>

  <button class="btn btn-info" onClick="byName()">Ordenar por nome</button>
  <button class="btn btn-info" onClick="byAge()">Ordenar por idade</button>

  <button class="btn btn-info" onClick="">Exibir apenas homens</button>
  <button class="btn btn-info" onClick="">Exibir apenas mulheres</button>
  <button class="btn btn-info" onClick="">Exibir todos</button>
</div>

  • Your question is what to call the console.log(users.sort(byAge)) when you click a button ?

  • No, by the.log console I’ve seen that the sort function is working, I need to understand how to order the list when I click the sort button

  • What is the difference between that and what I said ? To me it seems the same, except the detail of being a specific button, the order

  • briefly click on the order button by age, it does not work does not order, I want to know how to order the list that I created by the list function()

  • 1

    I seem to me that your question should be another, or else you got confused in the code. Still, if you want to sort by age when you click the button Ordenar por idade then don’t just change the onclick and its function as already ? Something like : <button class="btn btn-info" onClick="ordenarIdade()">Ordenar por idade</button>, and then on JS function ordernarIdade(){ users.sort(byAge); list(); }. That’s what you intend to do ?

1 answer

3


I already created the function to sort by age, I gave a console log and is ordering my question is how do I order only when you click the button

It seems that its difficulty is to call the function by the button, but, also a little logic, I decided to create a basic structure where a function shows the data, another function formats the display and other shows the filtered and ordered data.

Example:

var users = [{
    nome: 'Diego',
    idade: 23,
    sexo: 'M',
  },
  {
    nome: 'Gabriela',
    idade: 18,
    sexo: 'F',
  },
  {
    nome: 'José',
    idade: 30,
    sexo: 'M',
  },
  {
    nome: 'Maria',
    idade: 27,
    sexo: 'F'
  },
  {
    nome: 'Amanda',
    idade: 26,
    sexo: 'F'
  }
];

var show = 'all';

function textList(u) {
  return u.nome + " é " + (u.sexo == 'M' ? "Masculino" : "Feminino") + " e possui " + u.idade + " ano(s)";
}

function byName() {
  users.sort(function(a, b) {
    return a.nome < b.nome ? -1 : (a.nome > b.nome) ? 1 : 0;
  });
  list();
}

function byAge() {
  users.sort(function(a, b) {
    return a.idade < b.idade ? -1 : (a.idade > b.idade) ? 1 : 0;
  });
  list();
}

function showUsers(value) {
  show = value;
  list();
}

function list() {
  var listElement = document.getElementById("data");
  listElement.innerHTML = '';
  for (i = 0; i < users.length; i++) {
    if (show == 'all' || users[i].sexo == show) {
      var itemElement = document.createElement('li');
      itemElement.innerHTML = textList(users[i]);
      listElement.appendChild(itemElement);
    }
  }
}
list(); // init
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<ul id="data">
</ul>
<button class="btn btn-info" onClick="byName()">Ordenar por nome</button>
<button class="btn btn-info" onClick="byAge()">Ordenar por idade</button>

<button class="btn btn-info" onClick="showUsers('M');">Exibir apenas homens</button>
<button class="btn btn-info" onClick="showUsers('F');">Exibir apenas mulheres</button>
<button class="btn btn-info" onClick="showUsers('all');">Exibir todos</button>

It has been divided into functions so that when you click on the button you can execute the filter or ordering and immediately after updating the list display with the modification. On the buttons at the event onClick these functions were called with the appropriate parameters.

Important items:

  • 1

    Virgilio was exactly that, thanks for the help and links

Browser other questions tagged

You are not signed in. Login or sign up in order to post.