1

Tengo 4 funciones que hacen lo mismo solo que se les pasa distintos elementos de un objeto para poder ordenarlas en una tabla de manera ascendente o descendente. Por ejemplo:

function sortingNames(arr) {
  arr.sort(function(o1, o2) {
    if (o1.first_name > o2.first_name) {
      return 1; 
    } else if (o1.first_name < o2.first_name) {
      return -1;
    }
    return 0;
  });
}
function sortingLastNames(arr) {
  arr.sort(function(o1, o2) {
    if (o1.last_name > o2.last_name) {
      return 1; 
    } else if (o1.last_name < o2.last_name) {
      return -1;
    }
    return 0;
  });
}

Estas 2 funciones son casi los mismo solo por las variables first_name y last_name . No quiero repetirme ya intente agregando un argumento a la función pero no funciona

const infoTable = document.getElementById('info-table');
const sortName = document.getElementById('sort-name');
const sortLastName = document.getElementById('sort-last-name');
const sortAge = document.getElementById('sort-age');
const sortID = document.getElementById('sort-id');
const apiURL = "https://random-data-api.com/api/users/random_user?size=";
const size = 10;

let listUsers = [];

// Calculating the age
function getAge(dateBirth) {
  const today = new Date();
  const birthday = new Date(dateBirth);
  let age = today.getFullYear() - birthday.getFullYear();
  const month = today.getMonth() - birthday.getMonth(); 
  
  if (month < 0 || (month === 0 && today.getDate() < birthday.getDate())) {
    age--;
  }
  
  return age;
}

// Sort Strings
function sortingNames(arr) {
  arr.sort(function(o1, o2) {
    if (o1.first_name > o2.first_name) {
      return 1; 
    } else if (o1.first_name < o2.first_name) {
      return -1;
    }
    return 0;
  });
}
function sortingLastNames(arr) {
  arr.sort(function(o1, o2) {
    if (o1.last_name > o2.last_name) {
      return 1; 
    } else if (o1.last_name < o2.last_name) {
      return -1;
    }
    return 0;
  });
}

// Reverse Strings
function insortingNames(arr) {
  arr.reverse(function(o1, o2) {
    if (o1.first_name > o2.first_name) {
      return 1; 
    } else if (o1.first_name < o2.first_name) {
      return -1;
    }
    return 0;
  });
}
function insortingLastNames(arr) {
  arr.reverse(function(o1, o2) {
    if (o1.first_name > o2.first_name) {
      return 1; 
    } else if (o1.first_name < o2.first_name) {
      return -1;
    }
    return 0;
  });
}

// Sort ID's
function sortingID(arr) {
  arr.sort(function(o1, o2) {
    return o1.id - o2.id;
  });
}

// Reverse ID's
function insortingID(arr) {
  arr.sort(function (o1, o2) {
    return o2.id - o1.id;
  })
}

// Showing data on the table with this function
const displayInfo = (users) => {
  users.forEach((user) => {
    const { first_name, last_name, date_of_birth, address, id, email } = user;

    const age = getAge(date_of_birth);
  

    infoTable.innerHTML += `
      <tr role="row">
        <td role="cell">${first_name}</td>
        <td role="cell">${last_name}</td>
        <td role="cell">${age}</td>
        <td role="cell">${address.country}</td>
        <td role="cell">${id}</td>
        <td role="cell">${email}</td>
      </tr>
    `
  });
}

// Getting Data from API Random
async function getInfoUsers() {
  try {
    const response = await fetch(`${apiURL}${size}`);
    const result = await response.json();

    listUsers = [...result];
    
    displayInfo(result);
    
  } catch (error) {
    console.log(error);
  }
}

getInfoUsers();

// Event
sortName.addEventListener('click', () => {
  
  sortName.classList.toggle('abc');
  infoTable.innerHTML = '';
  
  if (sortName.classList.contains('abc')) {
    sortingNames(listUsers);

    displayInfo(listUsers);
  } else {
    insortingNames(listUsers);

    displayInfo(listUsers);
  }

});
sortLastName.addEventListener('click', () => {
  
  sortLastName.classList.toggle('abc');
  infoTable.innerHTML= '';

  if (sortLastName.classList.contains('abc')) {
    sortingLastNames(listUsers);

    displayInfo(listUsers);
  } else {
    insortingLastNames(listUsers);

    displayInfo(listUsers);
  }
});
sortID.addEventListener('click', () => {
  
  sortID.classList.toggle('abc');
  infoTable.innerHTML = '';

  if (sortID.classList.contains('abc')) {
    sortingID(listUsers);
    
    displayInfo(listUsers);
  } else {
    insortingID(listUsers);

    displayInfo(listUsers);
  }
});
@import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400&display=swap");

/* Reset */
html {
  box-sizing: border-box;
  font-size: 16px;
}

* {
  margin: 0;
  padding: 0;
}

*,
*::after,
*::before {
  box-sizing: inherit;
}

body {
  background: linear-gradient(to right, #eef0f1, #87888a); 
  font-family: "Montserrat", sans-serif;
  margin: 1rem;
}

thead {
  background-color: #e9d2e5;
}

/* Desktop */
table {
  table-layout: fixed;
  margin: 25px auto;
  background-color: #fff;
  max-width: 95%;
}

th, td {
  width: 250px;
  word-wrap: break-word;
}

table tbody tr:nth-child(odd) {
  background-color: #f4f4f7;
}

.content-table {
  border-collapse: collapse;
  font-size: 0.9em;
  
}

.content-table thead tr {
  color: #333;
  text-align: left;
}

.content-table thead tr p {
  display: inline-block;
}


th, td {
  border: 1px solid #87888a;
}

.content-table thead tr th {
  font-weight: normal;
  padding: 0.7rem 0.5rem 0.7rem 0.5rem;
}

td {
  padding: 1rem 0.5rem 1rem 0.5rem;
}

.header-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

i {
  font-size: 1rem;
  cursor: pointer;
}

/* Responsive */
@media only screen and (max-width: 760px) {
  /* Force table to not be like tables anymore */
  table, thead, tbody, th, td, tr {
    display: block;
  }

  /* Hide table headers (but not display: none; for accesibility */
  thead tr {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }

  /* Adding space between rows-groups */
  tr {
    margin: 0 0 1rem 0;
  }

  tr:nth-child(odd) {
    background: #ccc;
  }

  td {
    /* Behave like a row */
    width: 100%;
    border: none;
    border-bottom: 1px solid #eee;
    position: relative;
    padding-left: 50%; 
  }

  td:before {
    /* Now like a table header */
    position: absolute;
    /* Top/left values mimic padding */
    top: 0;
    left: 6px;
    width: 45%;
    padding: 1rem 0.5rem 1rem 0.63rem;
    white-space: nowrap;
  }

  td:nth-of-type(1):before { content: "First Name" }
  td:nth-of-type(2):before { content: "Last Name" }
  td:nth-of-type(3):before { content: "Age" }
  td:nth-of-type(4):before { content: "Nation" }
  td:nth-of-type(5):before { content: "ID" }
  td:nth-of-type(6):before { content: "E-Mail" }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://kit.fontawesome.com/1b3aa506e9.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="R4.css">
  <title>Solicitud R4</title>
</head>
<body>
  
  <table class="content-table" role="table">
    <thead role="rowgroup">
      <tr role="row">
        <th role="columnheader"><div class="header-line"><p>Name</p><i id="sort-name" class="fas fa-sort"></i></div></th>
        <th role="columnheader"><div class="header-line"><p>Last Name</p><i id="sort-last-name" class="fas fa-sort"></i></div></th>
        <th role="columnheader"><div class="header-line"><p>Age</p><i id="sort-age" class="fas fa-sort"></i></div></th>
        <th role="columnheader"><div class="header-line"><p>Nation</p></div></th>
        <th role="columnheader"><div class="header-line"><p>ID</p><i id="sort-id" class="fas fa-sort"></i></div></th>
        <th role="columnheader"><div class="header-line"><p>E-Mail</p></div></th>
      </tr>
    </thead>
    <tbody id="info-table" role="rowgroup">
      <!-- <tr role="row">
        <td role="cell">James</td>
        <td role="cell">Matman</td>
        <td role="cell">45</td>
        <td role="cell">USA</td>
        <td role="cell">43453456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Carl</td>
        <td role="cell">Deck</td>
        <td role="cell">33</td>
        <td role="cell">USA</td>
        <td role="cell">4345645456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Laura</td>
        <td role="cell">Dickson</td>
        <td role="cell">25</td>
        <td role="cell">USA</td>
        <td role="cell">46753956</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Ema</td>
        <td role="cell">Bostian</td>
        <td role="cell">29</td>
        <td role="cell">USA</td>
        <td role="cell">41253856</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Jaz</td>
        <td role="cell">Breackman</td>
        <td role="cell">31</td>
        <td role="cell">USA</td>
        <td role="cell">98453456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Lito</td>
        <td role="cell">Costafebre</td>
        <td role="cell">56</td>
        <td role="cell">ARG</td>
        <td role="cell">47753456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Rod</td>
        <td role="cell">Stewart</td>
        <td role="cell">57</td>
        <td role="cell">USA</td>
        <td role="cell">99453456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Tara</td>
        <td role="cell">Walsh</td>
        <td role="cell">21</td>
        <td role="cell">USA</td>
        <td role="cell">1473456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Dua</td>
        <td role="cell">Lipa</td>
        <td role="cell">23</td>
        <td role="cell">UK</td>
        <td role="cell">434021456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Enzo</td>
        <td role="cell">Perez</td>
        <td role="cell">31</td>
        <td role="cell">ARG</td>
        <td role="cell">40053456</td>
        <td role="cell">[email protected]</td>
      </tr> -->
    </tbody>
  </table>

  <script src="R4.js"></script>
</body>
</html>

1 respuesta 1

1

Ciertamente, se puede simplificar el código, no solo en evitar funciones casi iguales, también en otras cosas, como usar la variable global listUsers en vez de pasarla como parámetro, no es necesario y te sugiero hacer el cambio para evitar confusiones o variables extra.

En cuanto a:

No quiero repetirme ya intente agregando un argumento a la función pero no funciona

No basta con enviar el argumento, sino la forma de usarlo, por ejemplo, si el argumento es 'first_name', debes usarlo como índice para acceder a la propiedad correspondiente:

function miFuncion(property) {
    // Esto no va a funcionar, porque se intentará acceder a listUsers.property, que no existe
    console.log(listUsers.property);
    // Debes usar el argumento como índice, será como acceder a listUsers.first_name o listUsers['first_name'], que es lo mismo
    console.log(listUsers[property]);
}

Con dos funciones es suficiente para ordenar por las columnas que quieras, en cada una envías el nombre de propiedad y si el orden debe ser ascendente o descendente.

const infoTable = document.getElementById('info-table');
const sortName = document.getElementById('sort-name');
const sortLastName = document.getElementById('sort-last-name');
const sortAge = document.getElementById('sort-age');
const sortID = document.getElementById('sort-id');
const apiURL = "https://random-data-api.com/api/users/random_user?size=";
const size = 10;

let listUsers = [];

// Calculating the age
function getAge(dateBirth) {
  const today = new Date();
  const birthday = new Date(dateBirth);
  let age = today.getFullYear() - birthday.getFullYear();
  const month = today.getMonth() - birthday.getMonth(); 
  
  if (month < 0 || (month === 0 && today.getDate() < birthday.getDate())) {
    age--;
  }
  
  return age;
}

// Ordenar por propiedad de tipo cadena
// arr - Es el arreglo a ordenar
// property - Es la propiedad que se va a usar para ordenar
// reverse - Verdadero para orden descendente
function sortString(arr, property, reverse = false) {
    arr.sort((a, b) => a[property].localeCompare(b[property]));
    // Invertir arreglo cuando el parámetro sea verdadero
    if(reverse) {
        arr.reverse();
    }
}
// Funciona igual que la anterior, pero es específica para datos numéricos
function sortNumber(arr, property, reverse = false) {
    arr.sort((a, b) => a[property] - b[property]);
    if(reverse) {
        arr.reverse();
    }
}


// Showing data on the table with this function
const displayInfo = (users) => {
  users.forEach((user) => {
    const { first_name, last_name, date_of_birth, address, id, email } = user;

    const age = getAge(date_of_birth);
  

    infoTable.innerHTML += `
      <tr role="row">
        <td role="cell">${first_name}</td>
        <td role="cell">${last_name}</td>
        <td role="cell">${age}</td>
        <td role="cell">${address.country}</td>
        <td role="cell">${id}</td>
        <td role="cell">${email}</td>
      </tr>
    `
  });
}

// Getting Data from API Random
async function getInfoUsers() {
  try {
    const response = await fetch(`${apiURL}${size}`);
    const result = await response.json();

    listUsers = [...result];
    
    displayInfo(result);
    
  } catch (error) {
    console.log(error);
  }
}

getInfoUsers();

// Event
sortName.addEventListener('click', () => {
  sortName.classList.toggle('abc');
  infoTable.innerHTML = '';
  // Orden inverso si no contiene la clase abc
  let reverse = !sortName.classList.contains('abc');
  // Ordenar y mostrar
  sortString(listUsers, 'first_name', reverse);
  displayInfo(listUsers);
});

sortLastName.addEventListener('click', () => {
  sortLastName.classList.toggle('abc');
  infoTable.innerHTML= '';

  let reverse = !sortLastName.classList.contains('abc');
  sortString(listUsers, 'last_name', reverse);
  displayInfo(listUsers);
});

sortID.addEventListener('click', () => {
  sortID.classList.toggle('abc');
  infoTable.innerHTML = '';

  let reverse = !sortID.classList.contains('abc');
  sortNumber(listUsers, 'id', reverse);
  displayInfo(listUsers);
});
@import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400&display=swap");

/* Reset */
html {
  box-sizing: border-box;
  font-size: 16px;
}

* {
  margin: 0;
  padding: 0;
}

*,
*::after,
*::before {
  box-sizing: inherit;
}

body {
  background: linear-gradient(to right, #eef0f1, #87888a); 
  font-family: "Montserrat", sans-serif;
  margin: 1rem;
}

thead {
  background-color: #e9d2e5;
}

/* Desktop */
table {
  table-layout: fixed;
  margin: 25px auto;
  background-color: #fff;
  max-width: 95%;
}

th, td {
  width: 250px;
  word-wrap: break-word;
}

table tbody tr:nth-child(odd) {
  background-color: #f4f4f7;
}

.content-table {
  border-collapse: collapse;
  font-size: 0.9em;
  
}

.content-table thead tr {
  color: #333;
  text-align: left;
}

.content-table thead tr p {
  display: inline-block;
}


th, td {
  border: 1px solid #87888a;
}

.content-table thead tr th {
  font-weight: normal;
  padding: 0.7rem 0.5rem 0.7rem 0.5rem;
}

td {
  padding: 1rem 0.5rem 1rem 0.5rem;
}

.header-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

i {
  font-size: 1rem;
  cursor: pointer;
}

/* Responsive */
@media only screen and (max-width: 760px) {
  /* Force table to not be like tables anymore */
  table, thead, tbody, th, td, tr {
    display: block;
  }

  /* Hide table headers (but not display: none; for accesibility */
  thead tr {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }

  /* Adding space between rows-groups */
  tr {
    margin: 0 0 1rem 0;
  }

  tr:nth-child(odd) {
    background: #ccc;
  }

  td {
    /* Behave like a row */
    width: 100%;
    border: none;
    border-bottom: 1px solid #eee;
    position: relative;
    padding-left: 50%; 
  }

  td:before {
    /* Now like a table header */
    position: absolute;
    /* Top/left values mimic padding */
    top: 0;
    left: 6px;
    width: 45%;
    padding: 1rem 0.5rem 1rem 0.63rem;
    white-space: nowrap;
  }

  td:nth-of-type(1):before { content: "First Name" }
  td:nth-of-type(2):before { content: "Last Name" }
  td:nth-of-type(3):before { content: "Age" }
  td:nth-of-type(4):before { content: "Nation" }
  td:nth-of-type(5):before { content: "ID" }
  td:nth-of-type(6):before { content: "E-Mail" }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://kit.fontawesome.com/1b3aa506e9.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="R4.css">
  <title>Solicitud R4</title>
</head>
<body>
  
  <table class="content-table" role="table">
    <thead role="rowgroup">
      <tr role="row">
        <th role="columnheader"><div class="header-line"><p>Name</p><i id="sort-name" class="fas fa-sort"></i></div></th>
        <th role="columnheader"><div class="header-line"><p>Last Name</p><i id="sort-last-name" class="fas fa-sort"></i></div></th>
        <th role="columnheader"><div class="header-line"><p>Age</p><i id="sort-age" class="fas fa-sort"></i></div></th>
        <th role="columnheader"><div class="header-line"><p>Nation</p></div></th>
        <th role="columnheader"><div class="header-line"><p>ID</p><i id="sort-id" class="fas fa-sort"></i></div></th>
        <th role="columnheader"><div class="header-line"><p>E-Mail</p></div></th>
      </tr>
    </thead>
    <tbody id="info-table" role="rowgroup">
      <!-- <tr role="row">
        <td role="cell">James</td>
        <td role="cell">Matman</td>
        <td role="cell">45</td>
        <td role="cell">USA</td>
        <td role="cell">43453456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Carl</td>
        <td role="cell">Deck</td>
        <td role="cell">33</td>
        <td role="cell">USA</td>
        <td role="cell">4345645456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Laura</td>
        <td role="cell">Dickson</td>
        <td role="cell">25</td>
        <td role="cell">USA</td>
        <td role="cell">46753956</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Ema</td>
        <td role="cell">Bostian</td>
        <td role="cell">29</td>
        <td role="cell">USA</td>
        <td role="cell">41253856</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Jaz</td>
        <td role="cell">Breackman</td>
        <td role="cell">31</td>
        <td role="cell">USA</td>
        <td role="cell">98453456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Lito</td>
        <td role="cell">Costafebre</td>
        <td role="cell">56</td>
        <td role="cell">ARG</td>
        <td role="cell">47753456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Rod</td>
        <td role="cell">Stewart</td>
        <td role="cell">57</td>
        <td role="cell">USA</td>
        <td role="cell">99453456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Tara</td>
        <td role="cell">Walsh</td>
        <td role="cell">21</td>
        <td role="cell">USA</td>
        <td role="cell">1473456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Dua</td>
        <td role="cell">Lipa</td>
        <td role="cell">23</td>
        <td role="cell">UK</td>
        <td role="cell">434021456</td>
        <td role="cell">[email protected]</td>
      </tr>
      <tr role="row">
        <td role="cell">Enzo</td>
        <td role="cell">Perez</td>
        <td role="cell">31</td>
        <td role="cell">ARG</td>
        <td role="cell">40053456</td>
        <td role="cell">[email protected]</td>
      </tr> -->
    </tbody>
  </table>

  <script src="R4.js"></script>
</body>
</html>

Y todavía se puede reducir si creas una función para que los eventos no repitan código, por ejemplo:

function eventOrder(column, property, type = '') {
    // Limpiar la tabla
    infoTable.innerHTML = '';
    // Cambiar clase de la columna
    column.classList.toggle('abc');
    // Orden inverso si no contiene la clase abc
    let reverse = !column.classList.contains('abc');
    // Ordenar por cadena o número, dependiendo del tipo
    if(type == 'string') {
        sortString(listUsers, property, reverse);
    } else {
        sortNumber(listUsers, property, reverse);
    }
    // Actualizar tabla
    displayInfo(listUsers);
}

// La asignación de eventos queda con una sola línea
sortName.addEventListener('click', () => {
    eventOrder(sortName, 'first_name', 'string');
});
1
  • Muy bueno solo voy a tener que agregar los events que faltan. Está perfecto gracias! Commented el 26 may. 2021 a las 18:19

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.