javascriptarraysfunctioncallbackhigher-order-functions

why is my higher order function returning true and false?


I have to create my own higher order filter() function to filter an array of 10 words that only returns word that have 6 or more letters but my function is only returning true and false and not omitting words that are not 6 or more letters instead of actually returning the words in a new array. Do add additional code to execute the function?

Also I am not allowed to use the built-in filter function.

const wordArray = ["mine", "script", "function", "array", "javascript", "python", "coding", "html", "css", "bye"];
//myFilterFunction(HOF) takes an array (arr) and hypothetical function (fn) as arguments//
let myFilterFunction = (arr) => (fn) => {
    const newArray = [];
    for (let i = 0; i < arr.length; i++) {
        newArray.push(fn(arr[i]));
    }
    return newArray; //return a array
};
//myFilterFunction is used with an anonymous function to return whether each word is 6 or more   letters//
const printArray = myFilterFunction(wordArray)((word) => word.length >= 6);
//Output the result to the console//
console.log("this array only contains words that are 6 letters or more: " + printArray);

Solution

  • You were appending the result of the function that you have passed as argument into the array instead of passing the elements of array

    const wordArray = ["mine", "script", "function", "array", "javascript", "python", "coding", "html", "css", "bye"];
    //myFilterFunction(HOF) takes an array (arr) and hypothetical function (fn) as arguments
    let myFilterFunction = (arr) => (fn) => {
        const newArray = [];
        for (let i = 0; i < arr.length; i++) {
     
          fn(arr[i]) && newArray.push(arr[i]);
    //if the condition is true we are adding the element to newArray 
    
        }
        return newArray; //return a array
    };
    //myFilterFunction is used with an anonymous function to return whether each word is 6 or more   letters
    const printArray = myFilterFunction(wordArray)((word) => word.length >= 6);
    //Output the result to the console
    console.log("this array only contains words that are 6 letters or more: " + printArray);