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

316
Visualizações
Sort Array javascript according to sizes

I have an array which i am trying to sort according to real world sizes

["s", "m", "l", "xl", "xxl", "xs"].sort(function(a,b){ 
    if(a === "xs") 
});

I am getting this array as response and I have to modify it in front end I have tried to sort it out but i cant find suitable condition to do What should I do such that array is sorted in this order

["xs","s", "m", "l", "xl", "xxl"]

Even If any size is missing it should be in correct order for instance If medium size is not available it should be in correct order

["xs","s", "l", "xl", "xxl"]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use the index position of an ordered array:

const order = ["xs", "s", "m", "l", "xl", "xxl"];

const orderedArray = ["s", "m", "l", "xl", "xxl", "xs"].sort((a, b) => {
  return order.indexOf(a) - order.indexOf(b)
})

console.log(orderedArray) // ["xs", "s", "m", "l", "xl", "xxl"]

about 4 years ago · Juan Pablo Isaza Relatório

0

Start by creating an array of objects, with the corresponding sizes:

var sizes = [
  { size: 'xs', value: 0},
  { size: 's', value: 1},
  { size: 'm', value: 2},
  { size: 'l', value: 3},
  { size: 'xl', value: 4},
  { size: 'xxl', value: 5}
];

Then sort based on the values:

// sort by value
sizes.sort(function (a, b) {
  return a.value - b.value;
});
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use an object here as a dictionary.

Fetching data from object is much better than array

const sizes = {
  xs: 100,
  s: 200,
  m: 300,
  l: 400,
  xl: 500,
  xxl: 600,
};

const arr = ["s", "m", "l", "xl", "xxl", "xs"];
const result = arr.sort((a, b) => sizes[a] - sizes[b]);
console.log(result);

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