如何解决如何编写递归以输出嵌套消息?
有带有用户评论的数据:
const mockData = [{
'id': 1,'parentId': 2,'text': 'id 1','date': new Date('2020-03-11T13:12:20+03:00')
},{
'id': 2,'parentId': null,'text': 'id 2','date': new Date('2020-03-11T13:04:37+03:00')
},{
'id': 3,'text': 'id 3','date': new Date('2020-03-11T13:05:40+03:00')
},{
'id': 4,'parentId': 1,'text': 'id 4','date': new Date('2020-03-11T13:10:02+03:00')
},{
'id': 5,'parentId': 6,'text': 'id 5','date': new Date('2020-03-11T13:14:33+03:00')
},{
'id': 6,'text': 'id 6','date': new Date('2020-03-11T11:05:33+03:00')
}]
有必要显示parentId === null的消息,并在其下方显示相应的答案。就像常规聊天一样。
我开始写:
function sortByDate(data) {
return data.sort(function compare(a,b) {
return a.date - b.date;
});
}
export const findChildrenComments = (data,parentId = null) => {
return sortByDate(data.filter(comment => comment.parentId === parentId));
};
const convert = mockData => {
let arr = [];
const parentArr = findChildrenComments(data);
parentArr.forEach(element => {
arr.push(element)
const child1 = findChildrenComments(data,element.parentId)
});
};
但是如何将其转换为递归?
解决方法
const mockData = [
{ id: 1,parentId: 2,text: "id 1",date: new Date("2020-03-11T13:12:20+03:00") },{ id: 2,parentId: null,text: "id 2",date: new Date("2020-03-11T13:04:37+03:00") },{ id: 3,text: "id 3",date: new Date("2020-03-11T13:05:40+03:00") },{ id: 4,parentId: 1,text: "id 4",date: new Date("2020-03-11T13:10:02+03:00") },{ id: 5,parentId: 6,text: "id 5",date: new Date("2020-03-11T13:14:33+03:00") },{ id: 6,text: "id 6",date: new Date("2020-03-11T11:05:33+03:00") },].sort((a,b) => a.date - b.date);
const recursion = parentId =>
mockData.filter(c => c.parentId === parentId).map(c => ({ ...c,children: recursion(c.id) }));
console.log(recursion(null));
,
x = []
y = []
regex = re.compile("^([^,]*,[^,]*),(.*),$")
with open("a.csv") as f:
for line in f:
result = regex.search(line).groups()
x.append(float(result[0].replace(",",".")))
y.append(float(result[1].replace(",".")))
,
一个相当简单的递归函数将这样的数组展平为树将是makeForest
:
const makeForest = (id,xs) =>
xs .filter (({parentId}) => parentId == id)
.map (({id,parentId,...rest}) => ({id,...rest,children: makeForest (id,xs)}))
const mockData = [{id: 1,date: new Date("2020-03-11T13:12:20+03:00")},{id: 2,date: new Date("2020-03-11T13:04:37+03:00")},{id: 3,date: new Date("2020-03-11T13:05:40+03:00")},{id: 4,date: new Date("2020-03-11T13:10:02+03:00")},{id: 5,date: new Date("2020-03-11T13:14:33+03:00")},{id: 6,date: new Date("2020-03-11T11:05:33+03:00")}]
.sort((a,b) => a.date - b.date)
console .log (makeForest (null,mockData))
.as-console-wrapper {min-height: 100% !important; top: 0}
(SO administrivia:这样的问题太多了。我们需要找到一个确定的问题,并开始将其他问题标记为重复。我只是不确定什么是好的基本情况。这可能会做,因为唯一的不同寻常是最初的排序。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。