1function iterative(categories, parentCategory, level = 0) {
2 return categories
3 .filter((category) => parentCategory ? category.parent === parentCategory : !category.parent)
4 .map(category => {
5 category.level = level;
6 return category;
7 })
8 .sort((a,b) => a.name.localeCompare(b.name))
9 .reduce((acc, curr) =>{
10 const children = iterative(categories, curr.id, level+1)
11
12 acc.push(curr, ...children);
13 return acc;
14 }, [])
15 ;
16}
17