What could be causing my higher order function to unexpectedly return both true and false values?

I need to develop a custom higher order filter() function in order to filter out words with less than 6 letters from an array of 10 words. However, my current implementation is only returning true and false instead of actually filtering out the words that do not meet the criteria. How can I modify my code to achieve the desired outcome?

It's important to note that I am not permitted to use the built-in filter function for this task.

const wordArray = ["apple", "banana", "mango", "kiwi", "orange", "pear", "grape", "melon", "papaya", "guava"];
//myFilterFunction(HOF) takes an array (arr) and custom function (fn) as parameters//
let myFilterFunction = (arr) => (fn) => {
    const filteredArray = [];
    for (let i = 0; i < arr.length; i++) {
        if(fn(arr[i])) {
            filteredArray.push(arr[i]);
        }
    }
    return filteredArray; //return a new filtered array
};
//Utilize myFilterFunction with an anonymous function to check each word length//
const result = myFilterFunction(wordArray)((word) => word.length >= 6);
//Display the filtered array on the console//
console.log("Filtered array only containing words with 6 or more letters: " + result);

Answer №1

Instead of pushing the boolean expression result as a condition, use it to push the desired word like this

const termList = ["apple", "banana", "orange", "grape", "mango", "kiwi", "papaya", "pear"];
//filterWords function takes an array (arr) and callback function (cb) as arguments//
let filterWords = (arr) => (cb) => {
    const filteredArray = [];
    for (let i = 0; i < arr.length; i++) {
        if (cb(arr[i])) {
            filteredArray.push(arr[i]);   
        }
    }
    return filteredArray; //returning an array
};
//Using filterWords with an anonymous callback function to filter words that have more than 5 characters//
const resultArray = filterWords(termList)((term) => term.length >= 5);
//Outputting the filtered array to the console//
console.log("This array only contains words with 5 or more characters: " + resultArray);

Answer №2

You mistakenly added the result of the function passed as an argument to the array instead of passing individual elements from the array.

const wordArray = ["mine", "script", "function", "array", "javascript", "python", "coding", "html", "css", "bye"];
// The higher-order function (HOF) myFilterFunction takes an array (arr) and a 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 add the element to newArray 

    }
    return newArray; // Return an array
};
// Using myFilterFunction with an anonymous function to filter words that are 6 or more letters long
const printArray = myFilterFunction(wordArray)((word) => word.length >= 6);
// Output the filtered array to the console
console.log("This array contains only words that are 6 letters or longer: " + printArray);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Traversing through nested arrays within nested objects using AngularJS

In my project, I am utilizing angularjs 1 and dealing with a complex json object that has multiple levels of nesting. My goal is to use ng-repeat in order to access a nested array within the json structure. [{ "information": { "name": "simdi jinki ...

Using Node.js cluster in conjunction with ZeroMQ reply workers

One common question arises: "How can a ZeroMQ REPLY socket be set up as a worker?" The idea is to replace the typical example using an HTTP server with a ZeroMQ REPLY server, for instance: var cluster = require('cluster'), zmq = require(&ap ...

Tips for repairing a side bar and header with CSS when using a JS & jQuery scroller

I am working on a layout design and my goal is to have the left sidebar, right sidebar, and header remain fixed in place. Here is the CSS code I am using : #container { padding-left: 200px; /* Left Sidebar fullwidth */ padding-ri ...

Is it possible to dynamically change the 'amount' on a PayPal button or iframe?

My task is to create a checkout page that exclusively uses PayPal for payment processing. The challenge I face is that the purchase amount is not fixed; users can input the desired amount for their purchase (e.g. buying a £100 gift code). PayPal typicall ...

Ways to verify the state of JSON array elements

Currently, I am working on an app that involves calling a service where data is returned in an array format. The structure of the data is as follows: [ { "Image":null, "FirstName":null, "Active":false, "HallTicketNumber":0, "ReportingTime": ...

Geometric structures in the style of Minecraft: Hexagonal Voxel Design

I'm attempting to create a hexagonal map by following the example at . Is there a way to generate hexagons instead of cubes? Using the first option from the manual resulted in creating a hexagonal mesh and positioning it. However, the second option ...

Having trouble loading select fields using AJAX within Wordpress? Update and find a solution!

UPDATE: I am struggling to iterate through the response object and populate a select field using my ajax function. Although I have tried using a for loop instead of each(), the select field gets populated with "undefined". Any suggestions on how to resolve ...

Running multiple JavaScript servers simultaneously can be achieved by utilizing specific tools and

Currently, I am working on developing a Discord bot and have encountered some issues along the way that all required the same solution. The fix involved running separate batch files instead of running everything in my main file (index.js). I opted to use n ...

What is the best way to save the properties of elements in an array of objects within another array?

I have obtained attributes from objects within an array that I need to store in another array. Here is the data I am working with: https://i.sstatic.net/b0JtY.jpg My goal is to extract the `displays` name attribute and save it in the `opt[]` array, which ...

NodeJS is throwing a SyntaxError due to an unexpected identifier when trying to render on res.Render

When trying to send a variable using res.Render(), I am experiencing an error on the client side. I want to send an object that contains arrays: In NodeJs: var countries_lat_lng = []; trip.countries.forEach(country => { var countr ...

Tips for creating a responsive Livewire Pagination system

Looking to make Livewire pagination responsive? When using Bootstrap, simply add flex-wrap to the pagination class to ensure responsiveness. Component: class Index extends Component { use WithPagination; protected $paginationTheme = 'bootstr ...

Guide to retrieving JSON key and value using AJAX

Is there a way for me to retrieve my json object using the table header as the key and displaying the corresponding values in an HTML table? history:{1/22/20: 2, 1/23/20: 3, 1/24/20: 5, 2/1/20: 19, 2/10/20: 32, 2/11/20: 33, 2/12/20: 33, 2/2/20: 19, 2/20/2 ...

When the "next" button is clicked on Datatables, the next set of 10 items

I am currently working on creating a table with pagination using datatables. The data is being fetched via ajax, which returns 10 data entries at a time. However, I am facing an issue where the first call only fetches the initial 10 data from the ajax call ...

React: segregate state and functions away from the view, although encountering an excess of props to transmit

Experimenting with a new approach that keeps state definition and functions separate from components. For example: // Display.js const Display = (props) => { const { data, setData, action } = props; ... return <div>...</div>; } // Di ...

Encountered an issue accessing property 'Component' which is undefined during the webpack build of a React component plugin

I have developed a wrapper for my leaflet plugin called leaflet-arrowheads using react-leaflet. This component is designed to be installed as an npm package, imported, and used easily. The structure of the component is quite simple: import React from &apo ...

switching back and forth between the registration and login forms

<script> $(document).ready(function(){ $("#register_link").click(function() { $("#login_or_register").empty(); $("#login_or_register").load("register_form.php"); }); $("#login_link").click(function() { $("# ...

What is the best way to make changes to the DOM when the state undergoes a

I've programmed the box container to adjust dynamically based on input changes. For instance, if I entered 1, it will generate one box. However, if I modify the input to 2, it mistakenly creates 3 boxes instead of just 2. import React from 'rea ...

Unusual Characteristics of Synchronous Ajax Requests in JavaScript

First and foremost, I'd like to apologize if my approach seems unconventional. My background is primarily in C development, so I tend to tackle AJAX issues in a way that reflects my experience in C programming. The scenario at hand involves a script ...

Vue's unshift method only appends new items to the beginning of an

Could you help me with a problem similar to this one: The array I am working with looks like this: remate: {id:1, lotes: [{id:1, nombre: lalala}, {id:2, nombre: lololo}]} My issue arises when attempting to add new items to remate.lotes. While the push m ...

Modify the CSS properties of the asp:AutoCompleteExtender using JavaScript

Is there a way to dynamically change the CompletionListItemCssClass attribute of an asp:AutoCompleteExtender using JavaScript every time the index of a combobox is changed? Here is the code snippet: ajaxtoolkit: <asp:AutoCompleteExtender ID="autocom" C ...