如何获取嵌套数组中所有非嵌套项的长度?

9

数组的 .length 属性将返回数组中元素的数量。例如,下面的数组包含 2 个元素:

[1, [2, 3]] // 2 个元素,数字 1 和数组 [2, 3]。 假设我们想知道嵌套数组中非嵌套项的总数。在上面的情况下,[1,[2,3]] 包含 3 个非嵌套项,即 1、2 和 3。

示例

getLength([1, [2, 3]]) ➞ 3
getLength([1, [2, [3, 4]]]) ➞ 4
getLength([1, [2, [3, [4, [5, 6]]]]]) ➞ 6


2
根据您的示例,您只是在计算数组中所有元素的总数... 根据标题,所有函数的结果应该是2, 2, 2? - EugenSunic
1
NayeemAhmed - 你能给我们举一个@EugenSunic上面所说不正确的例子吗? - T.J. Crowder
4个回答

18
您可以使用.flat(Infinity)来展开数组,然后获取其长度。使用具有Infinity参数的.flat()将嵌套数组中的所有元素连接到外部数组中,从而允许您计算元素的数量:

const getLength = arr => arr.flat(Infinity).length;

console.log(getLength([1, [2, 3]])) // ➞ 3
console.log(getLength([1, [2, [3, 4]]])) // ➞ 4
console.log(getLength([1, [2, [3, [4, [5, 6]]]]])) // ➞ 6


1
flat(Infinity)是否“模拟”递归,无论如何都是一个聪明的解决方案? - EugenSunic
2
@EugenSunic 谢谢 :). 根据规范,当元素是数组且深度(即:Infinity > 0)时,它会递归调用FlattenIntoArray,因此它基本上允许我们展平无限嵌套的数组。 - Nick Parsons

5
你可以对每个数组使用 reduce 以如下方式查找:

function getLength(arr){
  return arr.reduce(function fn(acc, item) {
    if(Array.isArray(item)) return item.reduce(fn);
    return acc + 1;
  }, 0);
}


console.log(getLength([1, [2, 3]]))
console.log(getLength([1, [2, [3, 4]]]))
console.log(getLength([1, [2, [3, [4, [5, 6]]]]]))


4

递归计算不再递归的元素数量:

function getLength(a) {
    let count = 0;
    for (const value of a) {
        if (Array.isArray(value)) {
            // Recurse
            count += getLength(value);
        } else {
            // Count
            ++count;
        }
    }
    return count;
}

示例:

function getLength(a) {
    let count = 0;
    for (const value of a) {
        if (Array.isArray(value)) {
            count += getLength(value);
        } else {
            ++count;
        }
    }
    return count;
}

console.log(getLength([1, [2, 3]]));
console.log(getLength([1, [2, [3, 4]]]));
console.log(getLength([1, [2, [3, [4, [5, 6]]]]]));


2
您可以将嵌套数组或一个数组的长度相加。

function getLength(array) {
    let count = 0;
    for (const item of array) count += !Array.isArray(item) || getLength(item);
    return count;
}

console.log(getLength([1, [2, 3]]));
console.log(getLength([1, [2, [3, 4]]]));
console.log(getLength([1, [2, [3, [4, [5, 6]]]]]));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接