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

223
Visualizações
Sorting data and its children using Javascript

I have data. There are other data of the same type that have children in this data. I want to sort them all according to their 'id' fields, but I couldn't set up the algorithm scheme for it.

What I've tried:

const sortedData: [] = [];

function sortAscending(datas: Group[]) {
    sortedData.push(datas.sort((group1, group2) => group1.id - group2.id ));
    return sortedData;
}

With this code, I can only sort without children.

I tried to model the picture I wanted to describe: enter image description here

Note: The returned data will be mapped and used later.

Sample array:

    0:
      children: [{…}]
      id: 1
      name: "name1"
      [[Prototype]]: Object
    1:
      children: []
      id: 7
      name: "name2"
      [[Prototype]]: Object

The 'children' field also has 'children', 'id' and 'name' fields just like themselves. What I want is to sort both the data itself and the data in the children field in it according to their 'id' fields.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

first you need to know that array sort method sorts the array in-place it means it changes the array you pass to it. so

const rawData= [...] // your raw, un-sorted data

function sortAscending(data){...} // your function that does sorting

sortAscending(rawData) // after this, your array gets sorted 'in-place'

second, if your data has children and those children have their own children and you want them all be sorted ascending you need to write some recursive algorithm. for example:

function sortAscending(data){
  data.sort((group1, group2) => group1.id - group2.id));
  for(group of data){
     if (group.children.length) sortAscending(group.children);
  }
}
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