Deep count of elements of an array using JavaScript


Problem

We are required to write a JavaScript function that takes in a nested array of element and return the deep count of elements present in the array.

Input

const arr = [1, 2, [3, 4, [5]]];

Output

const output = 7;

Because the elements at level 1 are 2, elements at level 2 are 2 and elements at level 3 are 1, Hence the deep count is 7.

Example

Following is the code −

 Live Demo

const arr = [1, 2, [3, 4, [5]]];
const deepCount = (arr = []) => {
   return arr
   .reduce((acc, val) => {
      return acc + (Array.isArray(val) ? deepCount(val) : 0);
   }, arr.length);
};
console.log(deepCount(arr));

Code Explanation

We used the Array.prototype.reduce() method to iterate over the array and if at any iteration we encountered a nested array, we recursively called our function.

Output

7

Updated on: 17-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements