We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
已知数据如下:
const testData = [ { name: '大中华区', type: 'area', children: [ { name: '华北片区', type: 'region', children: [ { name: '北京', type: 'city', children: [ { name: '东城区', type: 'district', children: [ { name: '东华门街道专卖店', type: 'store' }, { name: '东四街门店', type: 'store' }, { name: '和平里专卖店', type: 'store' } ] }, { name: '朝阳区', type: 'district', children: [ { name: '亚运村旗舰店', type: 'store' }, { name: '朝外街道店', type: 'store' } ] } ] } ] }, { name: '华东片区', type: 'region', children: [ { name: '上海', type: 'city', children: [ { name: '黄浦区', type: 'district', children: [ { name: '佳佳旗舰店', type: 'store' } ] } ] }, { name: '青岛', type: 'city', children: [ { name: '黄岛区', type: 'district', children: [ { name: '蜊叉泊商业街门店', type: 'store' } ] } ] } ] } ] }, { name: '海外大区', type: 'area', children: [ { name: '欧洲', type: 'region', children: [ { name: '巴黎', type: 'city', children: [ { name: '第4区', type: 'district', children: [ { name: '圣安东尼大道旗舰店', type: 'store' } ] } ] } ] } ] } ];
请统计总的 area、region、city、district 和 store 的数量,并统计每个大区(area)下 region、city、district 和 store 的数量。效果如下:
参考代码:
主要用到了递归思想和 reduce 方法
reduce
const model = ['area', 'region', 'city', 'district', 'store']; console.group('总计'); display(model, testData); console.groupEnd(); testData.map(node => { console.group(node.name); display(model.slice(1), node.children); console.groupEnd(); }); function countNumber(type, data) { const _count = (arr) => { if (!(Array.isArray(arr) && arr.length)) { return 0; } if (arr[0].type === type) { return arr.length; } return arr.reduce((total, cur) => { return total + _count(cur.children); }, 0); }; return _count(data); } function display(model, data) { model.map(s => { const title = s.substr(0, 1).toUpperCase() + s.substr(1); const number = countNumber(s, data); console.log(`${title}: ${number}`); }); }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
已知数据如下:
请统计总的 area、region、city、district 和 store 的数量,并统计每个大区(area)下 region、city、district 和 store 的数量。效果如下:
参考代码:
The text was updated successfully, but these errors were encountered: