Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 622
Nayeem Ahmed Avatar asked Aug 15 '20 08:08

Nayeem Ahmed


People also ask

What does flat() do?

flat() The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Whats a flattened array?

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.

How do you loop through a nested array?

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 ...


1 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
like image 141
Nick Parsons Avatar answered Oct 02 '22 19:10

Nick Parsons