Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Product of numbers present in a nested array in JavaScript
We are required to write a JavaScript function that takes in an array of nested arrays of Numbers and some falsy values (including 0) and some strings as well and the function should return the product of number values present in the nested array. If the array contains some 0s, we should ignore them as well.
Example
The code for this will be ?
const arr = [
1, 2, null, [
2, 5, null, undefined, false, 5, [
1, 3, false, 0, 2
], 4, false
], 4, 6, 0
];
const recursiveMultiplication = arr => {
let prod = 1;
for(let i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])){
prod *= recursiveMultiplication(arr[i]);
}else{
prod *= arr[i] || 1;
};
};
return prod;
};
console.log(recursiveMultiplication(arr));
Output
57600
How It Works
The function uses recursion to traverse nested arrays. For each element:
- If it's an array, recursively call the function
- If it's a number, multiply it with the product
- If it's falsy (null, undefined, false, 0), it's treated as 1 using
arr[i] || 1
Alternative Implementation
Here's a cleaner version using Array.flat() with Infinity to flatten all nested levels:
const arr = [1, 2, [3, 4, [5, 0, 6]], 7, null, false];
const productOfNumbers = arr => {
return arr
.flat(Infinity)
.filter(item => typeof item === 'number' && item !== 0)
.reduce((product, num) => product * num, 1);
};
console.log(productOfNumbers(arr));
Output
5040
Comparison
| Method | Advantages | Disadvantages |
|---|---|---|
| Recursive | Memory efficient for deep nesting | More complex code |
| Array.flat() | Cleaner, more readable | Creates temporary flattened array |
Conclusion
Both approaches effectively calculate the product of numbers in nested arrays while ignoring falsy values. The recursive method is more memory-efficient, while the Array.flat() approach is more readable and concise.
