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

184
Vistas
Script JS transform array

Hi guys I have a little question about a script and a way to get an output format like :

hierarchicalCategories.lvl0 : Womens  
hierarchicalCategories.lvl1 : Womens > Accessories  
hierarchicalCategories.lvl2 : Womens > Accessories > Bags  
hierarchicalCategories.lvl3 : Womens > Accessories > Bags > Sport- & Travel Bags

My array is simply : ["Womens", "Accessories", "Bags", "Sport- & Travel Bags"]
So I tried to code a function and get my expected data but, I'm blocked on how get my current postion and the first postitions of my array until the begining.

let categories = ["Womens", "Accessories", "Bags", "Sport- & Travel Bags"];
let rootName = "hierarchicalCategories.lvl";

const reindexFunction = () => {
  let current_position = 0;
  let size = categories.length;
  for (current_position; current_position < size; current_position++) {
    let first = rootName + current_position;
    if (current_position !== 0) {
      let categ =
        categories[current_position - 1] +
        " " +
        ">" +
        " " +
        categories[current_position];
      console.log(first+":"+categ);
    } else {
      let categ = categories[current_position];
      console.log(first+":"+categ);
    }
  }
};

reindexFunction();

The result of this is:

hierarchicalCategories.lvl0:Womens
hierarchicalCategories.lvl1:Womens > Accessories
hierarchicalCategories.lvl2:Accessories > Bags
hierarchicalCategories.lvl3:Bags > Sport- & Travel Bags

I'm sure it's easy but I searched some method to make this I found nothing. Thank you for your help, tips.

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

0

Just iterate over the categories and get the categories from index 0 to the current index. I used the forEach, slice and join methods of arrays:

  • iterate over the categories with forEach
  • get the items from index 0 to the current index with slice
  • format the slice to the desired format with join

Note: console.log adds a space between each argument by default

let categories = ["Womens", "Accessories", "Bags", "Sport- & Travel Bags"];
let rootName = "hierarchicalCategories.lvl";

categories.forEach((c, i) => console.log(rootName+i, ':', categories.slice(0, i+1).join(' > ')))

about 4 years ago · Juan Pablo Isaza Denunciar

0

The most straight-forward solution coming to me mind would be to map the indexes of the categories array to strings that are built from joining all elements of the array up to the index.

I'm doing this using Array.prototype.map and utilizing the second argument it passes to the callback function, which is the index. The first argument would be the value itself, but we are not interested in that, that's why I called it _ and it's not used.

I'm not sure about the exact output format desired - you said transform array, so I assume the result should be another array. But in case that's not the case, is should be easy to adjust.

const categories = ['Womens', 'Accessories', 'Bags', 'Sport- & Travel Bags']
const rootName = 'hierarchicalCategories.lvl'

function buildHierarchicalCategories (categories) {
  return categories.map((_, i) =>
    `${rootName}${i} : ${categories.slice(0, i + 1).join(' > ')}`
  )
}

console.log(buildHierarchicalCategories(categories))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Or you can just keep the categories and add to them

let categories = ["Womens", "Accessories", "Bags", "Sport- & Travel Bags"];
let rootName = "hierarchicalCategories.lvl";
let level = "";
categories.map((e, index) => {
  level += e;
  console.log(rootName + index + " : " + level);
  level += " > ";
});

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