Home > Software design >  How can I sort table base on column data time ago
How can I sort table base on column data time ago

Time:03-16

Below is my html table which I get from csv file.

Name Role Last login
Dahril Admin 2 days ago
Sherwin Staff 1 week ago
Jeffrey Guest 2 weeks ago
Clyde Guest 1 month ago
MJ Staff 2 months ago
Ann Staff 1 year ago
Boy Admin 2 years ago

I need to sort the table based on the last-login column from recent to past.
How can I achieve this in Javascript?

CodePudding user response:

I would use moment to create a date object using the information.

While reading the CSV file line by line with a fileReader, 2 days ago has to be used like this: moment().subtract(2, "days")... For example.

So the strategy is to determine which time "range" to use and then, create a moment object that will be used to sort the rows.

let csv = `Dahril,Admin,2 days ago
Sherwin,Staff,1 week ago
Jeffrey,Guest,2 weeks ago
Clyde,Guest,1 month ago
MJ,Staff,2 months ago
Ann,Staff,1 year ago
Boy,Admin,2 years ago`

// An array to process rows
let rows = []

// Range posibilities
let possibilities = ["days", "weeks", "months", "years"]

// That loop would be inside a filReader
let lines = csv.split(/\n/)
lines.forEach(line => {
  //console.log(line)

  let parts = line.split(",")
  
  let user = parts[0] //  Dahril
  let role = parts[1] //  Admin
  let when = parts[2] //  2 days ago
  
  let when_number = parseInt(when)  //  2
  let when_range = when.split(" ")[1]  //  days
  
  // Add an "s" if missing
  if(when_range.substr(-1) !== "s"){
    when_range  = "s"
  }
  
  // Find the range possibility
  let when_index = possibilities.indexOf(when_range)
  if (when_index < 0){
    console.error(when_range   " is not found")
    return
  }
  //console.log(possibilities[when_index])
  
  // Create a moment object
  let comparableTime = moment().subtract(when_number,possibilities[when_index])

  // Push an object containing each piece of information AND the moment object
  rows.push({user,role,when,comparableTime})
})

// sort the rows beased on the moment objects
let sortedRows = rows.sort((a,b) => b.comparableTime - a.comparableTime)

// Show the result in table
let resultTable = document.querySelector("#result")
sortedRows.forEach(row => {
  let td_1 = document.createElement("td")
  td_1.innerText = row.user
  let td_2 = document.createElement("td")
  td_2.innerText = row.role
  let td_3 = document.createElement("td")
  td_3.innerText = row.when
  
  let tr = document.createElement("tr")
  tr.append(td_1)
  tr.append(td_2)
  tr.append(td_3)
  
  resultTable.append(tr)
})
td{
  border: 1px solid black;
  padding: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<table id="result"/>

Moment documentation: subtract

  • Related