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
Recursive multiplication in array - JavaScript
We need to write a JavaScript function that takes a nested array containing numbers, false values, zeros, and strings, then returns the product of all valid numbers. The function should ignore zeros and falsy values while recursively processing nested arrays.
Problem Statement
Given a nested array with mixed data types, we want to multiply only the truthy numeric values while ignoring zeros, null, undefined, false, and strings.
Solution
We'll use recursion to traverse nested arrays and multiply only valid numbers:
const arr = [1, 5, 2, null, [
2, 5, null, undefined, false, 5, [
1, 3, false, 0, 2
], 4, 2, 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));
576000
How It Works
The function uses the logical OR operator (||) to handle falsy values:
-
arr[i] || 1returns1for any falsy value (null, undefined, false, 0) - For truthy numbers, it returns the number itself
-
Array.isArray()checks if an element is a nested array for recursive processing
Step-by-Step Breakdown
Let's trace through the calculation:
// Main array: [1, 5, 2, null, [...], 4, 6, 0]
// Valid numbers: 1 × 5 × 2 × (nested result) × 4 × 6
// Nested array: [2, 5, null, undefined, false, 5, [...], 4, 2, false]
// Valid numbers: 2 × 5 × 5 × (inner nested) × 4 × 2
// Inner nested: [1, 3, false, 0, 2]
// Valid numbers: 1 × 3 × 2 = 6
// Final calculation: 1 × 5 × 2 × (2 × 5 × 5 × 6 × 4 × 2) × 4 × 6
// = 1 × 5 × 2 × 2400 × 4 × 6 = 576000
const testArray = [2, 0, 3, null, [4, false, 5]];
console.log("Test result:", recursiveMultiplication(testArray));
Test result: 120
Key Points
- Recursion handles arbitrary nesting levels
- Falsy values (0, null, undefined, false) are ignored by multiplying by 1
- The base case is when an element is not an array
- String values would also be treated as falsy in multiplication context
Conclusion
This recursive approach efficiently multiplies valid numbers in nested arrays while ignoring falsy values. The key insight is using the logical OR operator to substitute 1 for any falsy value, ensuring they don't affect the final product.
