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

145
Vistas
javascript sorting a json array by a given key

given

let jsons = [
    {
    "id": 10
    ...
  }, 
    {
    "id": 4
    ...
  }, 
    {
    "id": 1
    ...
  }, 
  ...


]

I want jsons to be sorted by the id e.g.

let jsons = [
    {
      "id": 1
      ...
    }, 
    {
      "id": 2
      ...
    }, 
    {
      "id": 3
      ...
    }, 
    ...
]

This is what I have done to do this (but its extremely inefficient)

let jsons = [
    {
    "id": 10
    
  }, 
    {
    "id": 4
    
  }, 
    {
    "id": 1
    
  }, 
  
]

let new_list = []
length = jsons.length
for(let i = 0; i < length; i++) {
  let index = 0
  let cur_lowest = 50000 // not sure how to get an infinite upper_bound
  for(let j = 0; j < jsons.length; j++) {
    if(jsons[j].id <= cur_lowest) {
        cur_lowest = jsons[j].id
      index = j
    }
  }
  new_list.push(jsons[index])
  jsons.splice(index, 1)
}
console.log(new_list);

So this works I did it here https://jsfiddle.net/xceybhLg/5/

But is there a simpler way? Preferably with like the sorted function I think it can attach on keys but reading the documentation I don't really understand it

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Why cant you use a simple sort function that accepts a list and the key against which the sort action is to be performed.

let jsons = [
  { "id": 10 },
  { "id": 4 },
  { "id": 1 },
];
function sortList(list, key) {
  return list.sort((a, b) => a[key] - b[key]);
}
const new_list = sortList(jsons, 'id');
console.log(new_list);

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