- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements