Answers for "sorting of categories and subcategories in js"

0

sorting of categories and subcategories in js

function iterative(categories, parentCategory, level = 0) {
  return categories
    .filter((category) => parentCategory ? category.parent === parentCategory : !category.parent)
    .map(category => {
       category.level = level;
       return category;
    })
    .sort((a,b) => a.name.localeCompare(b.name))
    .reduce((acc, curr) =>{
      const children = iterative(categories, curr.id, level+1)

      acc.push(curr, ...children);
      return acc;
    }, [])
  ;
}
Posted by: Guest on June-24-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language