Problem Statement:
Given an array of elements, we need to filter out only the numbers from the array.
Example:
Input: [1, 'a', 3, 'b', 5, 7, 'c', 9]
Output: [1, 3, 5, 7, 9]
Approach:
We can iterate through the array and check if each element is a number or not. If it's a number, we add it to a new array.
Here's a step-by-step breakdown of the approach:
1. Initialize an empty array to store the filtered numbers.
2. Iterate through each element of the input array.
3. Check if the current element is a number.
4. If it's a number, add it to the new array.
5. Finally, return the array containing only the filtered numbers.
function filterNumbersFromArray(arr) { // Initialize an empty array to store filtered numbers let filteredArray = [];
// Iterate through each element of the input array
for (let i = 0; i < arr.length; i++) {
// Check if the current element is a number
if (typeof arr[i] === 'number') {
// If it's a number, add it to the filtered array
filteredArray.push(arr[i]);
}
}
// Return the filtered array containing only numbers
return filteredArray;
}// Example usage
let inputArray = [1, ‘a’, 3, ‘b’, 5, 7, ‘c’, 9];
let resultArray = filterNumbersFromArray(inputArray);
console.log(resultArray); // Output: [1, 3, 5, 7, 9]
This JavaScript function filterNumbersFromArray takes an array arr as input and returns a new array containing only the numbers from the input array. It iterates through each element of the input array, checks if the element is a number using typeof, and if so, adds it to the filteredArray. Finally, it returns the filteredArray.
Complexities:
Time Complexity:
The time complexity of this approach is O(n), where n is the number of elements in the input array. This is because we need to iterate through each element of the array once.
Space Complexity:
The space complexity is also O(n), where n is the number of elements in the input array. This is because we are creating a new array to store the filtered numbers, which can potentially contain all the numbers from the input array.