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

93
Visualizações
Array items sorting in javascript

I have an array that will change in its sorting order of items after each and every call but I wanted them to be fixed as per my requirement on the client side. Example attached below.

array, for example, the indexes or the sorting order won't be the same, it changes every time

[
    {
        key: "foo"
    },
    {
        key: "bar"
    },
    {
        key: "baz"
    }
]

and this is what I want every time, no matter what the sorting order is.

[
    {
        key: "baz"
    },
    {
        key: "foo"
    },
    {
        key: "bar"
    }
]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Define the "priority" of every key in an object pre hand. Then, using Array#sort, reorder the array:

const priorities = { baz: 3, foo: 2, bar: 1 };

const reorder = (arr = []) =>
  arr.sort(({ key: a }, { key: b }) => priorities[b] - priorities[a]);

console.log( reorder([ { key: "foo" }, { key: "bar" }, { key: "baz" } ]) );
console.log( reorder([ { key: "bar" }, { key: "foo" }, { key: "baz" } ]) );
console.log( reorder([ { key: "baz" }, { key: "bar" }, { key: "foo" } ]) );

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