sorting of categories and subcategories in js

Solutions on MaxInterview for sorting of categories and subcategories in js by the best coders in the world

showing results for - "sorting of categories and subcategories in js"
Emmie
18 Feb 2016
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