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

273
Visualizações
Issue arranging values in ascending order

I am trying to arrange given values in ascending orders

const value = [
  { val: "11-1" },
  { val: "12-1b" },
  { val: "12-1a" },
  { val: "12-700" },
  { val: "12-7" },
  { val: "12-8" },
];

I am using code below to sort this in ascending order:

value.sort((a,b)=>(a.val >b.val)? 1:((b.val>a.val)?-1:0));

The result of this sort is in the order 11-1,12-1a, 12-1b, 12-7, 12-700, 12-8. However, I want the order to be 11-1,12-1a, 12-1b, 12-7, 12-8, 12-700.

How can I achieve that?

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

0

If you're only interested of sorting by the value after the hyphen you can achieve it with this code:

const value = [
  
  {val:'12-1'},
  {val:'12-700'},
  {val:'12-7'},
  {val:'12-8'},

];

const sorted = value.sort((a,b) => {
  const anum = parseInt(a.val.split('-')[1]);
  const bnum = parseInt(b.val.split('-')[1]);
  return anum - bnum;
});

console.log(sorted);

about 4 years ago · Juan Pablo Isaza Relatório

0

updated the answer as your question update here's the solution for this:

const value = [{ val: '11-1' }, { val: '12-1b' }, { val: '12-1a' }, { val: '12-700' }, { val: '12-7' }, { val: '12-8' }];
const sortAlphaNum = (a, b) => a.val.localeCompare(b.val, 'en', { numeric: true });
console.log(value.sort(sortAlphaNum));
about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to check for different values both before and after the hyphen and include checking for letters, the solution at the end will solve this.

Here's what I did:

Created a regex to split the characters by type:

var regexValueSplit = /(\d+)([a-z]+)?-(\d+)([a-z]+)?/gi;

Created a comparison function to take numbers and letters into account:

function compareTypes(alpha, bravo) {
  if (!isNaN(alpha) && !isNaN(bravo)) {
    return parseInt(alpha) - parseInt(bravo);
  }
  return alpha > bravo;
}

Split the values based on regexValueSplit:

value.sort((a, b) => {
  let valuesA = a.val.split(regexValueSplit);
  let valuesB = b.val.split(regexValueSplit);

This produces results as follows (example string "12-1a"):

[
  "",
  "12",
  null,
  "1",
  "a",
  ""
]

Then, since all the split arrays should have the same length, compare each value in a for loop:

  for (let i = 0; i < valuesA.length; i++) {
    if (valuesA[i] !== valuesB[i]) {
      return compareTypes(valuesA[i], valuesB[i]);
    }
  }
  // Return 0 if all values are equal
  return 0;

const value = [{
    val: "11-1"
  },
  {
    val: "12-1b"
  },
  {
    val: "12-1a"
  },
  {
    val: "12-700"
  },
  {
    val: "12-7"
  },
  {
    val: "12-8"
  },
];
var regexValueSplit = /(\d+)([a-z]+)?-(\d+)([a-z]+)?/gi;

function compareTypes(alpha, bravo) {
  if (!isNaN(alpha) && !isNaN(bravo)) {
    return parseInt(alpha) - parseInt(bravo);
  }
  return alpha > bravo;
}
value.sort((a, b) => {
  let valuesA = a.val.split(regexValueSplit);
  let valuesB = b.val.split(regexValueSplit);
  for (let i = 0; i < valuesA.length; i++) {
    if (valuesA[i] !== valuesB[i]) {
      return compareTypes(valuesA[i], valuesB[i]);
    }
  }
  return 0;
});
console.log(JSON.stringify(value, null, 2));

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