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

276
Visualizações
How to sort an array with parents and children objects with JavaScript?

I have an array with object, which I need to sort in a such way that first the parent object should appear, and then its children objects, and so on. However, when I try to find index of a parent object in array in order to push the children object after it, the findIndex() method returns -1. Can somebody point to the root of this problem, as I cannot clearly see why it does that. The code and data array that I'm using is written below.

const data = [
    {
        "_id": "0",
        "parent": null,
        "title": "All"
    }, {
        "_id": "61c0a9cb8f67e811d55abb2d",
        "parent": null,
        "title": "Electronics"
    }, {
        "_id": "61c0a9cb8f67e811d55abb2e",
        "parent": { "_id": "61c0a9cb8f67e811d55abb2d" },
        "title": "Phones"
    }, {
        "_id": "61c0a9cb8f67e811d55abb2f",
        "parent": { "_id": "61c0a9cb8f67e811d55abb2d" },
        "title": "Laptops"
    }, {
        "_id": "61c0a9cb8f67e811d55abb30",
        "parent": { "_id": "61c0a9cb8f67e811d55abb2d" },
        "title": "TVs"
    }, {
        "_id": "61c0a9cb8f67e811d55abb31",
        "parent": null,
        "title": "Literature"
    }, {
        "_id": "61c0a9cb8f67e811d55abb32",
        "parent": { "_id": "61c0a9cb8f67e811d55abb31"},
        "title": "Study Literature"
    }, {
        "_id": "61c0a9cb8f67e811d55abb33",
        "parent": { "_id": "61c0a9cb8f67e811d55abb31" },
        "title": "Fictional Literature"
    }, {
        "_id": "61c0a9cb8f67e811d55abb34",
        "parent": { "_id": "61c0a9cb8f67e811d55abb31" },
        "title": "Comic books"
    }, {
        "_id": "61c0a9cb8f67e811d55abb35",
        "parent": { "_id": "61c0a9cb8f67e811d55abb2e" },
        "title": "Smartphones"
    }, {
        "_id": "61c0a9cb8f67e811d55abb36",
        "parent": { "_id": "61c0a9cb8f67e811d55abb35" },
        "title": "Accessories"
    }
];


let parents = [];

data.forEach( element => {
    if( element.parent == null ) {
        parents.push(element);
    }
    else {
        let parentId = element.parent._id;
        let index = parents.findIndex(item => {
            item._id == parentId;
        });
        console.log(index);
        parents.splice(index+1, 0, element);
    }
});

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Using item => {parentId == item._id;} does require a 'return' to be used: item => {return parentId == item._id;} without the return the function is basically item => null; which is than seen as false by .findIndex() resulting in a -1

If you use the arrow function without the curly braces a return is implied (But limits you to single line expressions as a trade-off): item => parentId == item._id

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

about 4 years ago · Santiago Trujillo 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