w3resource

JavaScript: Number of arrays inside an array

JavaScript Array: Exercise-53 with Solution

Count Arrays Inside Array

Write a JavaScript program to count the number of arrays inside a given array.

Test Data:

([2,8,[6],3,3,5,3,4,[5,4]]) -> 2
([2,8,[6,3,3],[4],5,[3,4,[5,4]]]) -> 3

Sample Solution:

JavaScript Code-1:

// Function to count the number of arrays inside an array
function test(arr_nums){
    // Use filter to create an array containing only the arrays from the input array
    return arr_nums.filter(n => Array.isArray(n)).length;
}

// Test the function with an array containing nested arrays
arr_nums = [2, 8, [6], 3, 3, 5, 3, 4, [5, 4]];
console.log("Number of arrays inside the said array: " + test(arr_nums));

// Test the function with another array containing nested arrays
arr_nums = [2, 8, [6, 3, 3], [4], 5, [3, 4, [5, 4]]];
console.log("Number of arrays inside the said array: " + test(arr_nums));

Output:

Number of arrays inside the said array: 2
Number of arrays inside the said array: 3 

Flowchart :

JavaScript array flowchart: Number of arrays inside an array.

Live Demo :

See the Pen javascript-array-exercise-53 by w3resource (@w3resource) on CodePen.


JavaScript Code-2:

// Function to count the number of non-empty arrays inside an array
function test(arr_nums){
    // Use filter to create an array containing only non-empty arrays from the input array
    return arr_nums.filter(n => n.length).length;
}

// Test the function with an array containing nested arrays
arr_nums = [2, 8, [6], 3, 3, 5, 3, 4, [5, 4]];
console.log("Number of non-empty arrays inside the said array: " + test(arr_nums));

// Test the function with another array containing nested arrays
arr_nums = [2, 8, [6, 3, 3], [4], 5, [3, 4, [5, 4]]];
console.log("Number of non-empty arrays inside the said array: " + test(arr_nums));

Output:

Number of arrays inside the said array: 2
Number of arrays inside the said array: 3 

Flowchart :

JavaScript array flowchart: Number of arrays inside an array.

Live Demo :

See the Pen javascript-array-exercise-53-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that traverses an array and counts how many elements are arrays using Array.isArray().
  • Write a JavaScript function that uses reduce() to count nested arrays within a parent array.
  • Write a JavaScript function that iterates through an array and recursively counts arrays only at the top level.
  • Write a JavaScript function that validates the input to ensure it is an array and returns zero if it is not.

Go to:


PREV : Find NaN Indexes in Array.
NEXT : Javascript Stack Exercises Home.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.