
Problem
Solution
Submissions
Filter Array Based on Condition
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 8
Write a JavaScript function to filter an array based on a given condition. The function should take an array and a callback function as parameters, and return a new array containing only the elements that satisfy the condition specified by the callback function.
Example 1
- Input: arr = [1, 2, 3, 4, 5, 6], condition = (x) => x > 3
- Output: [4, 5, 6]
- Explanation:
- The input array contains numbers from 1 to 6.
- The condition function checks if each number is greater than 3.
- Testing: 1 > 3 (false), 2 > 3 (false), 3 > 3 (false).
- Testing: 4 > 3 (true), 5 > 3 (true), 6 > 3 (true).
- Only elements 4, 5, and 6 satisfy the condition.
- The filtered array [4, 5, 6] is returned.
- The input array contains numbers from 1 to 6.
Example 2
- Input: arr = ["apple", "banana", "cherry", "date"], condition = (str) => str.length > 5
- Output: ["banana", "cherry"]
- Explanation:
- The input array contains four string elements.
- The condition function checks if string length is greater than 5.
- Testing: "apple".length = 5 (not > 5, false).
- Testing: "banana".length = 6 (> 5, true).
- Testing: "cherry".length = 6 (> 5, true).
- Testing: "date".length = 4 (not > 5, false).
- Only "banana" and "cherry" satisfy the condition.
- The input array contains four string elements.
Constraints
- 1 ≤ arr.length ≤ 1000
- The callback function should return a boolean value
- Handle arrays with different data types
- Time Complexity: O(n) where n is the length of array
- Space Complexity: O(k) where k is the number of filtered elements
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Create an empty array to store filtered results
- Iterate through each element of the input array
- Apply the callback function to each element
- If callback returns true, add element to result array
- Use the built-in filter() method as an alternative approach
- Handle edge cases like empty arrays or null callbacks