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

247
Vistas
How to print file path with directory Indentation Nodejs

Printing file path with directory indentation. Input will be

[
  "/root/html/file/a.html",
  "/root/html/image/a.jpg",
  "/root/html/file/b.html",
  "/tmp/c.log"
]

Output needs to be like following,

- root
  - html 
     - file
       - a.html
       - b.html
     - image
       - a.jpg
- tmp
  - c.log

I couldn't find any solution. I guess it will be a recursive call with a tree structure. Any help would be appreciated.

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

0

You could map each file path of your input data into a simple tree-map structure and then recursively print this structure. Something like this (not tested and might still need to handle edge cases):

function processData(data) {
    const separator = "/";
    const tree = {};
    data.forEach(element => mapPathToTree(tree, element.split(separator).filter(part => part)));
    printTree(tree, 0);
}

function mapPathToTree(tree, pathParts) {
    if (pathParts && pathParts.length <= 1) {
        tree[pathParts[0]] = {};
        return;
    }
    const currPart = pathParts[0];
    let subTree = tree[currPart];
    if (!subTree) {
        subTree = {};
        tree[currPart] = subTree;
    }
    mapPathToTree(subTree, pathParts.slice(1));
}

function printTree(subTree, level) {
    for (const key in subTree) {
        console.log(" ".repeat(level).concat("- ").concat(key));
        printTree(subTree[key], level + 1);
    }
}

processData([
    "/root/html/file/a.html",
    "/root/html/image/a.jpg",
    "/root/html/file/b.html",
    "/tmp/c.log"
]);

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