Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
How can I sort table base on column data time ago

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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
SuperHero,Guest,3 years 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 fileReader
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"
  }
  
  // Make sure moment will not fail
  if (isNaN(when_number)){
    console.error(when + " does not start with a number.")
    return
  }
  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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda