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

114
Visualizações
Sort array of years (including BCE)

There is an array of objects containing a chemical element with it's discovery year:

[
   {"name": "hydrogen", "discovered": "1766"},
   {"name": "boron", "discovered": "1808"},
   {"name": "copper", "discovered": "9000 BCE"},
   {"name": "argon", "discovered": "1894"},
   {"name": "iron", "discovered": "before 5000 BCE"},
   {"name": "phosphorus", "discovered": "1669"}
]

What I want is to sort the array in terms of the year discovered, so the oldest (copper in this case) should be the first item and the recent(argon) should be the last item.

//It should look like this in the end:
[
   {"name": "copper", "discovered": "9000 BCE"},
   {"name": "iron", "discovered": "before 5000 BCE"},
   {"name": "phosphorus", "discovered": "1669"},
   {"name": "hydrogen", "discovered": "1766"},
   {"name": "boron", "discovered": "1808"},
   {"name": "argon", "discovered": "1894"}
]

The problem I encountered was the few keywords like "before", "BCE", "CE", that I don't know how to handle.

Is there any solution to handle this problem?

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

0

9000 BCE is same as year -9000.

You can simply treat those BCE (keyword before might be ignored, cause it contains BCE anyway) data strings as -year in sort function, as follows:

const data = [{name:"hydrogen",discovered:"1766"},{name:"boron",discovered:"1808"},{name:"copper",discovered:"9000 BCE"},{name:"argon",discovered:"1894"},{name:"iron",discovered:"before 5000 BCE"},{name:"phosphorus",discovered:"1669"}];

const res = data.sort((a, b) => {
  const numA = (a.discovered.includes("BCE") ? -1 : 1)
              * a.discovered.replace(/\D/g, '')
  const numB = (b.discovered.includes("BCE") ? -1 : 1)
              * b.discovered.replace(/\D/g, '')
  return numA - numB
})

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

about 4 years ago · Juan Pablo Isaza Relatório

0

Alright, so first you need to create a function that will convert the dates to a common format. In this example I will convert it to a number relative to 0 (year 0):

const beforeRegExp = new RegExp('(before )\\d*( BCE)');
const bceRegExp = new RegExp('\\d*( BCE)');

function toCommonDateFormat(date) {
  if (beforeRegExp.test(date)) {
    return date.replace("before ", "").replace(" BCE", "") * -1
  } else if (bceRegExp.test(date)) {
    return date.replace(" BCE", "") * -1
  } else {
    return date * 1;
  }
}

Now we can use this function in a sort function:

function compareDates(firstDate, secondDate) {
  return toCommonDateFormat(firstDate) - toCommonDateFormat(secondDate);
}

And now, to tie it all together:

const list = [{
    "name": "hydrogen",
    "discovered": "1766"
  },
  {
    "name": "boron",
    "discovered": "1808"
  },
  {
    "name": "copper",
    "discovered": "9000 BCE"
  },
  {
    "name": "argon",
    "discovered": "1894"
  },
  {
    "name": "iron",
    "discovered": "before 5000 BCE"
  },
  {
    "name": "phosphorus",
    "discovered": "1669"
  }
]

const beforeRegExp = new RegExp('(before )\\d*( BCE)');
const bceRegExp = new RegExp('\\d*( BCE)');

function toCommonDateFormat(date) {
  if (beforeRegExp.test(date)) {
    return date.replace("before ", "").replace(" BCE", "") * -1
  } else if (bceRegExp.test(date)) {
    return date.replace(" BCE", "") * -1
  } else {
    return date * 1;
  }
}

function compareDates(firstDate, secondDate) {
  return toCommonDateFormat(firstDate) - toCommonDateFormat(secondDate);
}

const orderedList = list.sort(function(firstItem, secondItem) {
  return compareDates(firstItem.discovered, secondItem.discovered);
});

console.log(orderedList);

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