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
flat() The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Flattening an array is a process of reducing the dimensionality of an array. In other words, it a process of reducing the number of dimensions of an array to a lower number.
After creating a JavaScript nested array, you can use the “push()” and “splice()” method for adding elements, “for loop” and “forEach()” method to iterate over the elements of the inner arrays, “flat()” method for reducing the dimensionality, and “pop()” method to delete sub-arrays or their elements from the nested ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With