Ordering data in a dynamic table using JavaScript

After receiving an array of objects in the form of a JSON file and using AJAX to display specific key-value pairs in a table, I am now faced with the task of sorting the rendered table. However, I am uncertain about the steps to take next.

<div id="data-table">
    <table id="html-data-table">
        <tr>
            <th>Name</th>
            <th>Age</th>
        </tr>
    </table>    
</div>

The JavaScript code responsible for generating the table is as follows:

newData.map(row => {
        let newRow = document.createElement("tr"); // new row is created
        Object.values(row).map((value) => {
            let cell = document.createElement("td"); // new data for the row is added
            cell.innerText = value;
            newRow.appendChild(cell);
        })
        mytable.appendChild(newRow);
    });

I am interested in sorting both columns individually. Can anyone suggest a method that can be used for this purpose?

Answer №1

Utilize the Array.sort() method to organize your dataset. In this scenario, I have included two buttons for sorting based on name and age:

const data = [
  { name: "dave", age: 22 },
  { name: "charlie", age: 32 },
  { name: "eve", age: 19 },
  { name: "alice", age: 27 },
  { name: "bob", age: 20 }
]

const tableBody = document.querySelector("#html-data-table tbody")
const sortByNameBtn = document.getElementById("sortName")
const sortByAgeBtn = document.getElementById("sortAge")

// DISPLAY UNORGANIZED TABLE
renderTable(data)

sortByNameBtn.addEventListener('click', (e) => {
  const sortedData = data.sort((a,b) => a.name.localeCompare(b.name))
  renderTable(sortedData)
})

sortByAgeBtn.addEventListener('click', (e) => {
  const sortedData = data.sort((a,b) => a.age - b.age)
  renderTable(sortedData)
})

function renderTable(tableData) {
  tableBody.innerHTML = ''
  
  tableData.map(row => {
    let newRow = document.createElement("tr"); 
   Object.values(row).map((value) => {
      let cell = document.createElement("td"); // new data for the row is added
      cell.innerText = value;
      newRow.appendChild(cell);
    })
    tableBody.appendChild(newRow);
  });
}
<div id="data-table">
  <table id="html-data-table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

<button id="sortName">Sort by Name</button>
<button id="sortAge">Sort by Age</button>

Answer №2

Here is a unique approach to sorting a table directly, without relying on any external data structures. All you need is the sortmode array, which indicates whether a column should be sorted as text or numerically.

const data=[{name:"Harry",age:32,height:183},{name:"Hermione",age:30,height:175},{name:"Ron",age:31,height:187},{name:"Hagrid",age:53,height:180},{name:"Ginny",age:27,height:170},{name:"Dumbledore",age:273,height:185}],
  sortmode=[0,1,1]; // 0: text, 1: numeric
  mytable=document.querySelector("#data-table tbody");

// Code for filling the table
data.map(row => {
 let newRow = document.createElement("tr");
 Object.values(row).map((value) => {
  
  let cell = document.createElement("td");
  cell.innerText = value;
  newRow.appendChild(cell);
 })
 mytable.appendChild(newRow);
});

// Sorting logic
document.querySelector("#data-table thead").onclick=ev=>{
 let col=[...ev.target.parentNode.children].indexOf(ev.target);
 [...mytable.children]
  .sort((a,b)=>
    sortmode[col]
     ? a.children[col].textContent - b.children[col].textContent
     : a.children[col].textContent.localeCompare(b.children[col].textContent)
   )
  .forEach(tr=>mytable.append(tr))

}
td:nth-child(n+2) {text-align:right}
<div id="data-table">
Simply click on the column headers to instantly sort the table:
<table id="html-data-table>">
   <thead>
    <tr><th>Name</th><th>Age</th><th>Height</th></tr>
   </thead><tbody></tbody>
</table>    
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding the second through eighth elements in a protractor using a CSS locator

Recently, I have been experimenting with protractor and facing a limitation when trying to reference elements. The only way to refer to them is through CSS, as they only have a class attribute provided. The issue arises when there are more than 7 elements ...

JSON.parse has thrown an unexpected token error with 'e'

Attempting to retrieve information from a JSON object stored in a file using FileReader. The contents of the json file are as follows: {"markers": [ { "point":new GLatLng(40.266044,-74.718479), "homeTeam":"Lawrence Library ...

Getting an image file to an API server using Node.js

I am looking to create an API server using node.js, and one of the requirements is to upload image files to it. While I have successfully implemented the logic for the GET method in my code, I am struggling with how to write the logic for the POST method ...

"Encountering problems with location search function on Instagram API for retrieving posts

I've been working on integrating two APIs – Instagram and Google Maps. While I've managed to get everything functioning smoothly, there's an issue with displaying "up to 20 pictures" around a specific location. I'm unsure why this in ...

Tips for integrating Google WebKit with AngularJS

Looking to enhance my application with Google WebKit functionality. My goal is to create a feature similar to Gmail's where hovering over the "+" symbol expands to display options such as "insert photos" and "insert links". I'm just starting out ...

Assigning a value to a select2 option based on data retrieved from a database

Is there a way to edit this form so that the select2 option can display selected data returned from the database and also be changeable? I've attempted to make these changes but am still unable to display the selected data. Thank you for any help :) ...

Adding hidden elements with jQuery: A comprehensive guide

I need assistance with adding the "is-hidden" class at this specific spot <span class="tag is-danger is-rounded is-small is-bolded span_notif_count ... "></span> As a beginner in jQuery, I am unsure about how to proceed. Could someon ...

Limit the 'contenteditable' attribute in table data to accept only integers

I have a question regarding editing table data row. Is there a way to restrict it to only integers? Thank you for your assistance! <td contenteditable="true" class="product_rate"></td> ...

Press the Enter key to submit

Encountering issues while trying to enter an event. Despite reviewing several posts on this matter, a solution has not been found yet. The project needs to function properly in Chrome, FF & IE (8,9,10,11), but it is currently not working on any browser. T ...

Challenges encountered while using JQuery Validation for a form submission for the second time (JQuery Steps)

Currently, I am implementing JQuery Steps for the registration form on my website. The registration process involves three steps: Personal > Company > Confirm. I have configured the form to display error messages in the "placeholder" if a textbox is ...

Issues with d3.js transition removal functionality not functioning as expected

Having an issue with a d3.js visualization that involves multiple small visualizations and a timeline. When the timeline changes, data points are supposed to be added or removed accordingly. Here is the code snippet responsible for updating: var channels ...

Incorporating Angular into the script code of the extension content

I am looking to customize text fields on a website using a chrome-extension. However, the website is built with Angular, so I need to modify the text fields using Angular code. To incorporate Angular in my extension's scope, I am attempting to declar ...

Utilize the $slots property when working with v-slot in your Vue application

When dealing with a specific use-case, it becomes necessary to retrieve the rendered width and height of a DOM element inside a slot. Typically, this can be achieved by accessing this.$slots.default[0].elm. However, complications arise when introducing sc ...

Combining multiple objects in an array to create a single object with the aggregated sum value can be achieved using JavaScript

I am working with an array that contains numbers of array objects, and I need to merge these arrays into a single array with unique values for content and the sum of values for total as shown in the desired result below. Any assistance would be greatly app ...

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

Issue with array filter not functioning correctly upon page refresh when utilizing vue-router

I have a method (shown below) that functions perfectly when I'm directed from a <router-link>. selectedSpaceObj() { if (!this.selectedSpace) { return {}; } else { return th ...

The video on mobile is not loading properly, as the play button appears crossed out

There seems to be an issue with GIFs not loading on mobile devices, even though they are implemented as mobile-ready. <video src="/wp-content/uploads/2017/09/5.mp4" preload="metadata" autoplay="autoplay" loop="loop" muted="muted" controls="controls" ...

What is the best approach for manipulating live data in localStorage using ReactJS?

I am working on creating a page that dynamically renders data from localStorage in real-time. My goal is to have the UI update instantly when I delete data from localStorage. Currently, my code does not reflect changes in real-time; I have to manually rel ...

Stopping a jQuery function from executing multiple times while it is already active - is it possible?

Currently, I am utilizing the http://jsfiddle.net/CqAU2/ plugin for image rotation on my website. The issue I am facing is that when the user clicks on the image box multiple times, it continues rotating each time. I want the click action to only be regi ...

Disable checkboxes upon page initialization

I am working with a form that includes checkboxes. Whenever the page loads, clicking on the checkboxes automatically checks them. However, I am looking for a solution where the checkboxes are disabled or not clickable during the page load process. Once th ...