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

186
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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