我有一个多维数组,我想知道它的最大深度。
我找到了这个灵魂,但它不适用于对象数组:
const getArrayDepth = (arr) => {
return Array.isArray(arr) ? 1 + Math.max(...arr.map(getArrayDepth)) : 0;
}
const a = [1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14];
const b = [{
"name": "Car Parts",
"children": [{
"name": "Body Parts",
"children": [{
"name": "Bumpers & Components",
"children": [{
"name": "Bumper Grilles",
"children": []
}]
}]
}, {
"name": "Engine Parts",
"children": [{
"name": "Alternators",
"children": []
}, {
"name": "Injectors",
"children": []
}]
}]
}, {
"name": "Wheels",
"children": [{
"name": "Alloy Wheels",
"children": []
}]
}, {
"name": "Lubricants & Coolants",
"children": []
}];
console.log(`A: ${getArrayDepth(a)} ✓`);
console.log(`B: ${getArrayDepth(b)} X (should be 4) `);
如何转换此代码以适用于我的数组?
最佳答案
参数arr
要么是一个数组,要么不是。如果不是,则它要么是带有 children
数组(具有元素)的对象,要么不是。如果不是,则返回 0。否则,对 children
进行递归。
const getArrayDepth = (arr) => {
return Array.isArray(arr) ? // if arr is an array, recurse over it
1 + Math.max(...arr.map(getArrayDepth)) :
Array.isArray(arr.children) && arr.children.length ? // if arr is an object with a children property, recurse over the children
1 + Math.max(...arr.children.map(getArrayDepth)) :
0; // otherwise, it's 0
}
const a = [1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14];
const b = [{
"name": "Car Parts",
"children": [{
"name": "Body Parts",
"children": [{
"name": "Bumpers & Components",
"children": [{
"name": "Bumper Grilles",
"children": []
}]
}]
}, {
"name": "Engine Parts",
"children": [{
"name": "Alternators",
"children": []
}, {
"name": "Injectors",
"children": []
}]
}]
}, {
"name": "Wheels",
"children": [{
"name": "Alloy Wheels",
"children": []
}]
}, {
"name": "Lubricants & Coolants",
"children": []
}];
console.log(`A: ${getArrayDepth(a)} ✓`);
console.log(`B: ${getArrayDepth(b)} X (should be 4) `);
这又是,使用 if 语句而不是嵌套三元组。我认为这样更清楚一些,但这实际上只是一个意见。
const getArrayDepth = (arr) => {
if (Array.isArray(arr)) {
// if arr is an array, recurse over it
return 1 + Math.max(...arr.map(getArrayDepth));
}
if (arr.children && arr.children.length) {
// if arr is an object with a children property, recurse over the children
return 1 + Math.max(...arr.children.map(getArrayDepth));
}
return 0;
}
const a = [1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14];
const b = [{
"name": "Car Parts",
"children": [{
"name": "Body Parts",
"children": [{
"name": "Bumpers & Components",
"children": [{
"name": "Bumper Grilles",
"children": []
}]
}]
}, {
"name": "Engine Parts",
"children": [{
"name": "Alternators",
"children": []
}, {
"name": "Injectors",
"children": []
}]
}]
}, {
"name": "Wheels",
"children": [{
"name": "Alloy Wheels",
"children": []
}]
}, {
"name": "Lubricants & Coolants",
"children": []
}];
console.log(`A: ${getArrayDepth(a)} ✓`);
console.log(`B: ${getArrayDepth(b)} X (should be 4) `);
关于javascript - JS如何获取多维数组的最大深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59162497/