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

106
Vistas
array of strings to tree data structure?

There is data returned from server containing an array of strings as hierarchy like this:

var array = [
 "house.bedroom.bed",
 "house.kitchen.spoon",
 "house.kitchen.knife",
 "house.bedroom.sofa",
 "house.bedroom.tv",
 "plants.trees",
 "house.birds.parrot.grey"
 ]

i have successful made a tree data structure as object out of it to make Output the data in tree form below:

  house
    bedroom
      bed
      sofa
      tv
    kitchen
      spoon
      knife
    birds
      parrot
        grey
  plants
    trees

and is there any way to pick a string? for example of asked "kitchen" i want to return all related to that string like this:

house.kitchen.knife
house.kitchen.spoon

Here the codes that i learned:

function find([key, values], string, temp = []) {
    var result;
    temp = temp.concat(key);
    if (key === string) {
        return temp.slice(1).join('.');
    }
    values.some(a => result = find(a, string, temp));
    return result;
}


var result = array.reduce((r, s) => {
        ('root.' + s).split('.').reduce((a, item) => {
            var array = a.find(([v]) => v === item);
            if (!array) {
                a.push(array = [item, []]);
            }
            return array[1];
        }, r);
        return r;
    }, []).pop();

console.log(find(result, 'kitchen'));
console.log(result);

my output is:

house.kitchen
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I propose to filter the original array

const data = ["house.bedroom.bed","house.kitchen.spoon", "house.kitchen.knife","house.bedroom.sofa","house.bedroom.tv",
 "plants.trees","house.birds.parrot.grey"];
 
 
 const result = data.filter((path) => path.split('.').includes('kitchen'));
 
 console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

about 4 years ago · Juan Pablo Isaza Denunciar

0

I believe I understand what you're asking. I would solve this problem with recursion.

function parse(items) {
   return items.reduce((acc, item) => {
      const k = item.slice(0, item.indexOf('.'))
      const v = item.slice(item.indexOf('.') + 1).split('.')
      
      const newItem = {
        [k]: v.length > 1 ? parse(v) : v
      }

      return Object.assign(acc, newItem)
   }, { })
}

This is not a complete solution but should get the general idea across. For each item in the array, split it off into a key and a value. The key will be the string before the first ., and the value with either be the single string after that ., or an object containing children.

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