首页 > 解决方案 > 如何递归地计算作为对象项数组的特定、自身重复的子数据结构的最大嵌套出现次数?

问题描述

嗨,我的后端得到了对象,看起来像这样:

 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);

但我得到一个错误的号码,谁能告诉我我做错了什么,我将不胜感激?

标签: javascriptarraysobjectrecursiondata-structures

解决方案


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; }


推荐阅读