Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!