Search code examples
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 are pushing the boolean expression result of the condition instead use that as a condition to push the desired word like so

    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++) {
            if (fn(arr[i])) {
                newArray.push(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);