Search code examples
javascriptarraysrecursiondepth-first-search

How do I recursively find the highest number in a deeply nested array of objects


Given this deeply nested array of objects. I would like to find the highest comment id

    const comments = [
  {
    id: 1,
    text: "First comment!",
    parentId: null,
    comments: [
      {
        id: 2,
        text: "Reply to comment 1",
        parentId: 1,
        comments: []
      },
      {
        id: 3,
        text: "Another reply to comment 1",
        parentId: 1,
        comments: [ ]
      }
    ]
  },
  {
    id: 5,
    text: "Second comment!",
    parentId: null,
    comments: [
      {
        id: 6,
        text: "Reply to comment 5",
        parentId: 5,
        comments: []
      },
    ]
  },
];

This is what I have tried

const getGreatest = (arr, greatest = -Infinity) => {
  for (let i = 0; i < arr.length; i++) {
    let comment = arr[i];
    if (Array.isArray(comment.comments) && comment.comments.length > 0) {
       greatest = Math.max(greatest , comment.id)
        getGreatest(comment.comments, greatest);
    }
  }
  return greatest; //returns 5
};

I know another way is to flatten the array of objects and then find the highest number but if I would like to do it in recursion, how could I do it?


Solution

  • I've added some comments (!) to the code to indicate the changes. Basically you forgot to do something with the return value of the recursive call, and moving the Math.max outside of the if will make it work when the object being tested has no comments array itself.

     const comments = [
      {
        id: 1,
        text: "First comment!",
        parentId: null,
        comments: [
          {
            id: 2,
            text: "Reply to comment 1",
            parentId: 1,
            comments: []
          },
          {
            id: 3,
            text: "Another reply to comment 1",
            parentId: 1,
            comments: [ ]
          }
        ]
      },
      {
        id: 5,
        text: "Second comment!",
        parentId: null,
        comments: [
          {
            id: 6,
            text: "Reply to comment 5",
            parentId: 5,
            comments: []
          },
        ]
      },
    ];
    
    const getGreatest = (arr, greatest = -Infinity) => {
      for (let i = 0; i < arr.length; i++) {
        let comment = arr[i];
    
        // this needs to happen regardless of whether comment.comments is an array
        greatest = Math.max(greatest, comment.id);
    
        if (Array.isArray(comment.comments)) {
    
            // don't forget to do something with the result of the recursive call!
            greatest = getGreatest(comment.comments, greatest);
        }
      }
      return greatest;
    };
    
    console.log(getGreatest(comments));