0

I want to sort parameters: id, salary and age at the click of a button. Suppose I have to dynamically clean my table (deleteRow), sort and then display the data again. However, seems to be difficult. Can somebody help me? Is there a better way?

JavaScript:

const butt = document.getElementById('button');
const swTable = document.getElementById('table').getElementsByTagName('tbody')[0];
const url = 'http://dummy.restapiexample.com/api/v1/employees';

function fetchFromUrl(url) {
  return fetch(url).then(function(resp) {
    return resp.json()
  });
}

function createElement(nameOfTag, text) {
  const element = document.createElement(nameOfTag);
  const content = document.createTextNode(text);
  element.appendChild(content);
  return element;
}

function createTable(data) {
  const table = document.createElement('tr');
  const {
    id,
    employee_name,
    employee_salary,
    employee_age
  } = data;

  table.appendChild(createElement('td', id))
  table.appendChild(createElement('td', employee_name))
  table.appendChild(createElement('td', employee_salary))
  table.appendChild(createElement('td', employee_age))
  return table;
}

fetchFromUrl('http://dummy.restapiexample.com/api/v1/employees')
  .then(data => {
    data.forEach(result => {
      const row = createTable(result);
      swTable.appendChild(row);
    })
  });
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>JS</title>

  <body>
    <table id=table>
      <thead>
        <th><button id=id> id </button> </th>
        <th><button id=name> employee name </button> </th>
        <th><button id=salary> employee salary </button> </th>
        <th><button id=age>  employee age </button> </th>
        </tr>
      </thead>
      <tbody>

      </tbody>

    </table>

    <script type="module" src='main.js' type="text/javascript">
    </script>
  </body>

</html>
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • What have you tried? What error do you come up with? Help us help you. Is there a better way is too broad of a question. – Jabberwocky May 23 '19 at 17:10
  • 1
    Please read https://stackoverflow.com/help/what-to-do-instead-of-deleting-question – Samuel Liew May 24 '19 at 06:21
  • 3
    Please do not delete a question if someone has spent time composing an answer and posting it. If the answer is helpful to you, it will probably be helpful to future users and visitors. You can accept @zagkaretos's answer by clicking on the checkmark, but by no means are you obligated to. – Mari-Lou A May 24 '19 at 07:43

1 Answers1

6

Using plain JavaScript, you can use a function for sorting the data array and then replace old tbody with the new one.

For example:

function sortByField(field) {
  if (field == 'id') {
    data.sort((a,b) => (Number(a.id) > Number(b.id)) ? 1 : ((Number(b.id) > Number(a.id)) ? -1 : 0)); 
  } else if (field == 'name') {
    data.sort((a,b) => (a.employee_name > b.employee_name) ? 1 : ((b.employee_name > a.employee_name) ? -1 : 0)); 
  } else if (field == 'salary') {
    data.sort((a,b) => (Number(a.employee_salary) > Number(b.employee_salary)) ? 1 : ((Number(b.employee_salary) > Number(a.employee_salary)) ? -1 : 0)); 
  } else if (field == 'age') {
    data.sort((a,b) => (Number(a.employee_age) > Number(b.employee_age)) ? 1 : ((Number(b.employee_age) > Number(a.employee_age)) ? -1 : 0)); 
  }

  var old_tbody = document.getElementById('tbody');
  var new_tbody = document.createElement('tbody');
  new_tbody.setAttribute('id', 'tbody');
  data.forEach(result => {
    const row = createTable(result);
    new_tbody.appendChild(row);
  });
  old_tbody.parentNode.replaceChild(new_tbody, old_tbody);
}

And add onclick event handlers on buttons:

onclick="sortByField('id')"

Here you can find a working example.

Note that I used Number to convert strings to numbers while sorting.

Of course, you can use Underscore library to perform the sorting, JQuery library to select html elements etc.

And take a look here on different ways you can sort an array of objects.

lzagkaretos
  • 2,842
  • 2
  • 16
  • 26
  • @Izagkaretos Great solution, thank you very much. However, I'm wondering if the data can be loaded straight from the api, instead of copying (var data = [{"id": "7150", "employee_name": "vanja1", "employee_salary": "45454" etc.) ? –  May 23 '19 at 17:30
  • Sure, you can load the data array as you wish. I used a fixed array, because I couldn't load from `http://dummy.restapiexample.com` endpoint from `https://plnkr.co`. – lzagkaretos May 23 '19 at 17:32