Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

84
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda