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?
There may be a better way but let me explain my process.
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.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)