Search code examples
javascriptalgolia

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?


Solution

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