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

182
Vistas
Algolia Hierarchy: Organize array for indexing

I have this array

["Fruits > Citrus > Orange", "Accessories > Bracelets"]

And I need to turn it to:

{
  "lvl0": ["Fruits", "Accessories"],
  "lvl1": ["Fruits > Citrus", "Accessories > Bracelets"],
  "lvl2": ["Fruits > Citrus > Orange"]
}

How would you handle this with a reducer? I've gotten close using Lodash zip but I'm kinda losing my mind

Anybody have a cool function to do this?

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

0

There may be a better way but let me explain my process.

  1. First I splitted individually and sorted descending no of elements. This was done so the first element has the highest no of levels which I'm later going to use to decide the no of levels.
  2. Then I ran reduce on sorted array. In the first If statement I'm initializing the levels in the accumulator object. That if statement will be accessed only for the first element.
    After that I'm pushing subarrays to individual arrays based on the level

Well in this specific example sorting is not even necessary since it is already sorted.

let a = ["Fruits > Citrus > Orange", "Accessories > Bracelets"]
let res = a.map((el)=> el.split(" > ")).sort((a,b) => b.length-a.length).reduce((acc,curr)=>{
    let levels = curr.length;
  if(!Object.keys(acc).length){
    for(i=0; i<levels;i++){
        acc[`lvl${i}`]=[]
    }
  }
  for(i=0; i<levels;i++){
        acc[`lvl${i}`].push(curr.slice(0,i+1).join(" > "))
  }
  
  return acc;
},{})

console.log(res)

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