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
Recursion in array to find odd numbers and push to new variable JavaScript
We are required to write a recursive function, say pushRecursively(), which takes in an array of numbers and returns an object containing odd and even properties where odd is an array of odd numbers from input array and even an array of even numbers from input array. This has to be done using recursion and no type of loop method should be used.
Syntax
const pushRecursively = (arr, len = 0, odd = [], even = []) => {
// Base case: if we've processed all elements
if (len >= arr.length) {
return { odd, even };
}
// Recursive case: process current element and continue
arr[len] % 2 === 0 ? even.push(arr[len]) : odd.push(arr[len]);
return pushRecursively(arr, len + 1, odd, even);
};
Example
const arr = [12, 4365, 76, 43, 76, 98, 5, 31, 4];
const pushRecursively = (arr, len = 0, odd = [], even = []) => {
if (len < arr.length) {
arr[len] % 2 === 0 ? even.push(arr[len]) : odd.push(arr[len]);
return pushRecursively(arr, ++len, odd, even);
}
return {
odd,
even
}
};
console.log(pushRecursively(arr));
{ odd: [ 4365, 43, 5, 31 ], even: [ 12, 76, 76, 98, 4 ] }
How It Works
The function uses four parameters:
- arr - The input array to process
- len - Current index (starts at 0)
- odd - Array to collect odd numbers
- even - Array to collect even numbers
While the len variable reaches the end of array, we keep calling the function recursively, each time pushing the odd values to odd array and the evens to even array. Once the len variable equals the length of array, we exit out of the function returning the object containing both arrays.
Alternative Approach
Here's a cleaner recursive implementation without modifying external arrays:
const separateNumbers = (arr) => {
if (arr.length === 0) {
return { odd: [], even: [] };
}
const [first, ...rest] = arr;
const result = separateNumbers(rest);
if (first % 2 === 0) {
result.even.unshift(first);
} else {
result.odd.unshift(first);
}
return result;
};
const numbers = [12, 4365, 76, 43, 76, 98, 5, 31, 4];
console.log(separateNumbers(numbers));
{ odd: [ 4365, 43, 5, 31 ], even: [ 12, 76, 76, 98, 4 ] }
Conclusion
Recursive array processing eliminates the need for loops by breaking the problem into smaller subproblems. Each recursive call processes one element and delegates the rest to the next call until the base case is reached.
