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

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

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

Tags:

Javascript