Implementing Array.prototype.filter in JavaScript
The Array.prototype.filter() method is a fundamental tool in JavaScript for creating new arrays containing only elements that satisfy a specific condition. This challenge asks you to implement this method from scratch, reinforcing your understanding of array manipulation and higher-order functions. Successfully implementing filter will allow you to concisely and efficiently extract subsets of data from arrays based on custom criteria.
Problem Description
Your task is to implement the filter method as a new function that can be added to the Array.prototype. This function should take a callback function as an argument. The callback function will be invoked for each element in the array, and should return a boolean value indicating whether the element should be included in the new array. The filter method should return a new array containing only the elements for which the callback function returned true. The original array should not be modified.
Key Requirements:
- Callback Function: The
filtermethod must accept a callback function as its only argument. This function should accept three arguments: the current element, the index of the current element, and the array itself. - Boolean Return Value: The callback function must return a boolean value.
trueindicates the element should be included in the new array, andfalseindicates it should be excluded. - New Array: The
filtermethod must return a new array. It should not modify the original array. - Element Order: The elements in the new array should maintain the same order as they appeared in the original array.
- Handling Non-Function Callback: If the provided callback is not a function, the
filtermethod should return an empty array.
Expected Behavior:
When called on an array, filter should iterate through each element, execute the callback function with that element, and add the element to the new array if the callback returns true.
Edge Cases to Consider:
- Empty Array: What should happen if the input array is empty?
- Callback Always Returns True: What should happen if the callback function always returns
true? - Callback Always Returns False: What should happen if the callback function always returns
false? - Non-Function Callback: What should happen if the provided argument is not a function?
- Null or Undefined Elements: How should the callback handle
nullorundefinedelements within the array? (Treat them as any other element).
Examples
Example 1:
Input: [1, 2, 3, 4, 5].filter(function(x) { return x % 2 === 0; })
Output: [2, 4]
Explanation: The callback function checks if each number is even. Only 2 and 4 satisfy this condition, so they are included in the new array.
Example 2:
Input: [1, "hello", true, 42, "world"].filter(function(x) { return typeof x === 'string'; })
Output: ["hello", "world"]
Explanation: The callback function checks if each element is a string. Only "hello" and "world" satisfy this condition.
Example 3:
Input: [1, 2, 3].filter(null)
Output: []
Explanation: The callback is null, which is not a function. The method should return an empty array.
Example 4:
Input: [].filter(function(x) { return x > 0; })
Output: []
Explanation: The input array is empty. The filter method should return an empty array.
Constraints
- The input array can contain any type of data (numbers, strings, booleans, objects, etc.).
- The callback function can perform any operation and return a boolean value.
- The time complexity of your implementation should be O(n), where n is the length of the input array.
- The space complexity of your implementation should be O(n) in the worst case (when all elements satisfy the filter condition).
Notes
- Remember that
filtershould not modify the original array. - Consider using a
forloop orforEachto iterate through the array. - Pay close attention to the arguments passed to the callback function.
- Think about how to handle the edge case where the callback is not a function.
- The goal is to replicate the behavior of the built-in
Array.prototype.filter()method.