How to get the length of all non-nested items in nested arrays?

Viewed 708

The .length property on an array will return the number of elements in the array. For example, the array below contains 2 elements:

[1, [2, 3]] // 2 elements, number 1 and array [2, 3] Suppose we instead wanted to know the total number of non-nested items in the nested array. In the above case, [1, [2, 3]] contains 3 non-nested items, 1, 2 and 3.

Examples

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

4 Answers

You can flatten the array using .flat(Infinity) and then get the length. Using .flat() with an argument of Infinity will concatenate all the elements from the nested array into the one outer array, allowing you to count the number of elements:

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

You can use reduce on each array it'll find like this :

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

Recursively count the elements that you don't recurse into:

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

Live Example:

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

You could just add the lengths for nested array or one.

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

Related