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

149
Visualizações
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 Respostas
Responde à pergunta

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 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