Goal: create a
myFilter(arr, callback)function that mimics the behavior ofArray.prototype.filter.
Write a myFilter function that takes an array arr and a callback function. The function should return a new array containing only those elements from arr for which the callback returned true. Do not use the built-in Array.prototype.filter method.
This task helps to deeper understand the workings of higher-order functions in JavaScript, such as filter, map, and reduce. Understanding their internal mechanics is key to writing clean, efficient, and functional code.
callback. If it returns true, add the element to the new array./**
* The myFilter function, implemented using a for loop.
* @param {Array} arr - The input array.
* @param {Function} callback - The predicate function.
* @returns {Array} - A new filtered array.
*/
function myFilter(arr, callback) {
// 1. Create an empty array to store the results.
const filteredArray = [];
// 2. Start a loop to iterate over each element of the source array.
for (let i = 0; i < arr.length; i++) {
// 3. Call the callback for the current element `arr[i]`.
// If it returns `true`, the condition is met.
if (callback(arr[i], i, arr)) {
// 4. Add the element to our new array.
filteredArray.push(arr[i]);
}
}
// 5. Return the new array with the filtered elements.
return filteredArray;
}Step-by-step code explanation:
function myFilter(arr, callback) { ... }
myFilter function, which takes two arguments: arr (the array to be filtered) and callback (the function that will determine whether to include an element).const filteredArray = [];
filteredArray. This is where the elements that pass the check will be stored. We will return this array at the end.for (let i = 0; i < arr.length; i++) { ... }
for loop to iterate over each element in the source array arr.let i = 0: We start with the first element (index 0).i < arr.length: The loop will continue as long as i is less than the total number of elements in the array.i++: After each iteration, we increment i by 1 to move to the next element.if (callback(arr[i], i, arr)) { ... }
callback.arr[i]: We pass the current element to the callback.i: We pass its index.arr: We pass the original array itself.if (...): If the callback returns true, the condition is considered met.filteredArray.push(arr[i]);
if statement is true, we add the current element arr[i] to our filteredArray.return filteredArray;
filteredArray, which now contains all the filtered elements.Why this way:
for loop is often the fastest way to traverse an array, as it has minimal overhead.Your implementation should support the standard callback function signature for filter: callback(element, index, array).
element: The current element being processed in the array.index (optional): The index of the current element.array (optional): The array being traversed.const numbers = [1, 2, 3, 4, 5];
const even = myFilter(numbers, (num) => num % 2 === 0);
// even should be [2, 4]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const longWords = myFilter(words, (word) => word.length > 6);
// longWords should be ['exuberant', 'destruction', 'present']myFilter.Goal: create a
myFilter(arr, callback)function that mimics the behavior ofArray.prototype.filter.
Write a myFilter function that takes an array arr and a callback function. The function should return a new array containing only those elements from arr for which the callback returned true. Do not use the built-in Array.prototype.filter method.
This task helps to deeper understand the workings of higher-order functions in JavaScript, such as filter, map, and reduce. Understanding their internal mechanics is key to writing clean, efficient, and functional code.
callback. If it returns true, add the element to the new array./**
* The myFilter function, implemented using a for loop.
* @param {Array} arr - The input array.
* @param {Function} callback - The predicate function.
* @returns {Array} - A new filtered array.
*/
function myFilter(arr, callback) {
// 1. Create an empty array to store the results.
const filteredArray = [];
// 2. Start a loop to iterate over each element of the source array.
for (let i = 0; i < arr.length; i++) {
// 3. Call the callback for the current element `arr[i]`.
// If it returns `true`, the condition is met.
if (callback(arr[i], i, arr)) {
// 4. Add the element to our new array.
filteredArray.push(arr[i]);
}
}
// 5. Return the new array with the filtered elements.
return filteredArray;
}Step-by-step code explanation:
function myFilter(arr, callback) { ... }
myFilter function, which takes two arguments: arr (the array to be filtered) and callback (the function that will determine whether to include an element).const filteredArray = [];
filteredArray. This is where the elements that pass the check will be stored. We will return this array at the end.for (let i = 0; i < arr.length; i++) { ... }
for loop to iterate over each element in the source array arr.let i = 0: We start with the first element (index 0).i < arr.length: The loop will continue as long as i is less than the total number of elements in the array.i++: After each iteration, we increment i by 1 to move to the next element.if (callback(arr[i], i, arr)) { ... }
callback.arr[i]: We pass the current element to the callback.i: We pass its index.arr: We pass the original array itself.if (...): If the callback returns true, the condition is considered met.filteredArray.push(arr[i]);
if statement is true, we add the current element arr[i] to our filteredArray.return filteredArray;
filteredArray, which now contains all the filtered elements.Why this way:
for loop is often the fastest way to traverse an array, as it has minimal overhead.Your implementation should support the standard callback function signature for filter: callback(element, index, array).
element: The current element being processed in the array.index (optional): The index of the current element.array (optional): The array being traversed.const numbers = [1, 2, 3, 4, 5];
const even = myFilter(numbers, (num) => num % 2 === 0);
// even should be [2, 4]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const longWords = myFilter(words, (word) => word.length > 6);
// longWords should be ['exuberant', 'destruction', 'present']myFilter.The code editor is intentionally hidden on mobile.
Believe me, it's for the best: I am protecting you from the temptation to code in less-than-ideal conditions. A small screen and a virtual keyboard are not the best tools for a programmer.
📖 Now: Study the task, think through the solution. Act like a strategist.
💻 Later: Sit down at your computer, open the site, and implement all your ideas comfortably. Act like a code-jedi!