给定这个深度嵌套的对象数组。我要找最高评论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: []
},
]
},
];
这是我试过的
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
};
我知道另一种方法是展平对象数组然后找到最大的数字但是如果我想在递归中这样做,我该怎么做?
非常感谢。