javascript - 如何递归地计算作为对象项数组的特定、自身重复的子数据结构的最大嵌套出现次数?
问题描述
嗨,我的后端得到了对象,看起来像这样:
reaction {[
some data about reaction ,
reactions: {[
some data about reaction ,
reactions: {[
some data about comment,
reactions:
]}
]}
]}
嵌套反应可以是无限的,并且反应中可以有任意数量的反应。
我尝试计算所有反应:
reaction.flat(Infinity).length
我也尝试:
const getArrayDepth = arr => {
if (Array.isArray(arr)) {
return 1 + Math.max(...arr.map(getArrayDepth));
}
if (arr.reactions&& arr.reactions.length) {
return 1 + Math.max(...arr.reactions.map(getArrayDepth));
}
return 0;
};
和
const totalReactions = arr => arr.reduce((count, current) => count + current.reactions.length, 0);
但我得到一个错误的号码,谁能告诉我我做错了什么,我将不胜感激?
解决方案
function getMaximumReactionsFoldCount(reactions, foldCount = 0) {
return reactions.reduce((count, item) => {
if (item.hasOwnProperty('reactions')) {
count = Math.max(
count,
getMaximumReactionsFoldCount(item.reactions, ++foldCount)
);
}
return count;
}, foldCount);
}
const reactions = [{ // 1
foo: 'foo',
bar: 'bar',
reactions: [{ // 1a-2
fooBar: 'foo-bar',
bazBiz: 'bar-biz',
reactions: [{ // 1a-2-3
foo: 'foo',
bar: 'bar',
reactions: [{ // 1a-2-3-4
// ... more ...
}],
}],
buzBoz: 'buz-boz',
}],
baz: 'baz',
}, {
fooFoo: 'foo-foo',
barBar: 'bar-bar',
reactions: [{ // 1b-2
fooBarBaz: 'foo-bar-baz',
reactions: [{ // 1b-2-3
foo: 'foo',
bar: 'bar',
reactions: [{ // 1b-2-3-4a
fooBar: 'foo-bar',
bazBiz: 'bar-biz',
reactions: [{ // 1b-2-3-4a-5
foo: 'foo',
bar: 'bar',
reactions: [{ // 1b-2-3-4a-5-6
reactions: [{ // 1b-2-3-4a-5-6-7
reactions: [{ // 1b-2-3-4a-5-6-7-8
// ... more ...
}],
bizzz: 'BIZZZ',
}],
buzzz: 'BUZZZ',
}],
bozzz: 'BOZZZ',
}],
buzBoz: 'buz-boz',
}],
baz: 'baz',
}, {
fooFoo: 'foo-foo',
barBar: 'bar-bar',
reactions: [{ // 1b-2-3-4b
fooBarBaz: 'foo-bar-baz',
reactions: [ // 1b-2-3-4b-5
// ... more ...
],
bizBuzBoz: 'biz-buz-boz',
}],
bazBaz: 'baz-baz',
}],
bizBuzBoz: 'biz-buz-boz',
}],
bazBaz: 'baz-baz',
}];
console.log(
'getMaximumReactionsFoldCount(reactions) ...',
getMaximumReactionsFoldCount(reactions)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
推荐阅读
- c# - Revit API - 创建 View3D 时如何设置北向?
- python - 可以在弹性搜索中访问dense_vector的值吗?
- python - (2003, "Can't connect to MySQL server on "0.0.0.0" (tiemd out) ) 错误
- api - Flutter Stateless Class 和 Statefull 类坚持使用
- c# - 字典的清晰实例化和新实例化之间的区别
- android - 我在拦截器和改造方面做错了什么?
- python - 在 Python 中读取包含多个对象的 JSON 文件
- arrays - C计算三个数组的每次组合乘法之和时超时
- github - 为我正在观看的所有 GitHub 存储库设置自定义通知规则
- php - 使用 WHERE IN 查询以分号分隔的值列