Home > Enterprise >  Sort tree structured object by another object
Sort tree structured object by another object

Time:09-22

I have the following unsorted file structure:

const files: File[] = [
    
    {info: {name: "Part 3"},
    contents: 
    [
        {info: {name: "05 Chapter"}, contents: [], isHidden: false},
        {info: {name: "10 Chapter"}, contents: [], isHidden: false},
        {info: {name: "03 Annex"}, contents: [], isHidden: false}
    ], 
    isHidden: false
    },

    {info: {name: "Part 1"},
    contents: 
    [
        {info: {name: "05 Chapter"}, contents: [], isHidden: false},
        {info: {name: "10 Annex"}, contents: [], isHidden: false},
        {info: {name: "03 Chapter"}, contents: [], isHidden: false}
    ], 
    isHidden: false}
]

I'd like to sort this unsorted file tree object by files.info.name based on another input object (which is a simple bookmark structured object) that look like this:

const bookmark = [
    
  { 
    part: "Part 1", 
    chapters: 
    [
      {
        name: "03 Annex", 
        chapters: [] 
      },
      {
        name: "05 Chapter", 
        chapters: [] 
      },
      { 
        name: "10 Chapter", 
        chapters: [] 
      }
    ] 
  }, 
  { 
    part: "Part 3", 
    chapters: 
    [
      {
        name: "03 Chapter", 
        chapters: [] 
      },
      {
        name: "05 Chapter", 
        chapters: [] 
      },
      { 
        name: "10 Annex", 
        chapters: [] 
      }
    ]
  }
]

I have the following so far but I don't think this would go through each level.

  // sortFilesByBookmark sorts the files to show by a given bookmark object
export function sortFilesByBookmark(files: File[], bookmark){
    
    files.sort(function(a, b){  
        return bookmark.indexOf(a.info.name) - bookmarkArray.indexOf(b.info.name);
      });

}

CodePudding user response:

Use a recursive function

interface XFile {
  info: { name: string };
  isHidden: boolean;
  contents: XFile[];
}

interface Bookmark {
  // You should consider naming `part` & `name` the same
  part?: string;
  name?: string;
  chapters: Bookmark[];
}

export function sortFilesByBookmark(files: XFile[], bookmarks: Bookmark[]): XFile[] {
  // Sort file as bookmarks
  const sorted = files.sort((a, b) => {
    return bookmarks.findIndex(x => a.info.name === (x.part || x.name))
      - bookmarks.findIndex(x => b.info.name === (x.part || x.name));
  })
  // Nest sort
  sorted.forEach((f, ix) => {
    const bk = bookmarks.find(x => f.info.name === (x.part || x.name));
    f.contents = sortFilesByBookmark(f.contents, bk.chapters);
  })
  
  return sorted;
}
  • Related