Creating a custom function that replicates the functionality of the JavaScript native 'filter' method, utilizing two arguments

While working on a functional programming challenge I came across online, the task was to create a custom 'filter' method in JavaScript. This method should take two arguments - a collection and a test function that returns either 'true' or 'false. It should then iterate over the collection using an 'each' function previously implemented and return the resulting array.

I've successfully completed the initial part of the exercise by developing a function that mimics JS's forEach method:

var each = function(collection, iterator) {
  if(Array.isArray(collection)){
   for(var i = 0; i < collection.length; i++){
    iterator(collection[i],i,collection);
  }
  } else if (typeof collection === "object"){
    for(var property in collection){
      iterator(collection[property], property, collection);
    }

   }else{
     console.log("you messed up!");
  }
 };

To test my function, I used the following example:

function returnOdds(currentEl) {
   return currentEl % 2 !== 0;
}
 console.log(filter([1, 2, 3], returnOdds)); // output: 1, 3

Now, I am unsure how to incorporate my 'each' function within the 'filter' function. I'm questioning whether it is legal to call 'each' on the 'collection' parameter inside filter.

Alternatively, can I use the 'test' parameter as a function to check if each element in the collection is odd or even?

function filter(collection, test) {
   var odd = function(each()){
    each(collection){
       if(collection[i] !== 0){
            return odd;
          }
         }
       }
    }

I am uncertain if any of these approaches are correct or feasible.

Answer №1

To complete the implementation of the filter() function, you need to create a new array that contains only the values that pass a certain test. One way to achieve this is by using the existing each() method as shown below:

var filter = function(collection, test) {
  var results = [];
  each(collection, function(val) {
    if (test(val)) {
      results.push(val);
    }
  });
  return results;
};

You can then use this function by passing in an array and a reference to another function that determines whether each item should be included in the resulting array:

var oddNumbers = filter([1, 2, 3], returnOdds);

Check out this demo for a better understanding: https://jsfiddle.net/4rj7phot/

This is how the function works:

  1. An empty array is created to store the filtered results.
  2. The each() function is used to iterate through each item in the provided collection.
  3. For each item, the test function is called to determine whether it passes the test. If it does, the item is added to the results array.
  4. Finally, the results array is returned.

Any additional argument validation can be handled on your end, such as ensuring that the test parameter is actually a function.

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

The git clone operation encounters a problem with the error message: unable to connect, connection refused on localhost port 80

Currently for my project, I'm utilizing isomorphic-git. However, when I try to implement the git.clone function, I encounter the error message Error: connect ECONNREFUSED 127.0.0.1:80. To provide an example of what I am attempting to achieve: import ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

Enhance your navbar on user scroll with Bootstrap 4 by moving or adding elements dynamically

I recently built a Wordpress site using Bootstrap 4.5 for the front-end, marking my first experience with Bootstrap. The site currently features the standard sticky Bootstrap 4 navbar as shown in the code snippet below: <header> <nav c ...

Ways to unveil a concealed div element using JavaScript

If javascript is disabled, I want to hide a div. If javascript is enabled, however, I don't want to rely on using the <noscript> tag due to issues in Chrome and Opera. Instead, my approach is as follows: <div id="box" style="display:none"> ...

Unable to postpone the utilization of data in Vue until after retrieving the value from the database

I am facing an issue where I need to compare a string obtained from Firebase in document.check1 with specific strings (hardcoded in the function below) and display content accordingly. Currently, I know how to trigger this comparison on button click, but I ...

Enhancing Your WordPress Menu with Customized Spans

I have a WordPress menu structured like this: <div id="my_custom_class"> <ul class="my_custom_class"> <li class="page_item"><a href="#">page_item</a> <ul class='children'> <li class="page_item chil ...

Viewing the availability of various locations within a JSON table based on the user's specific locale

I am working with a JSON table: [ { "fr": { "name": "chien", "name_plurial": "chiens" }, "en": { "name": "dog", "name_plurial": "dogs" } }, { "fr": { "name": "chat", "name_plurial": "chats" }, "en": { "name": "cat", "name_plurial": " ...

the ever-changing dimensions of a PDF document

I'm attempting to display a PDF using an iframe, but I want the height of the viewer to match the document's height, meaning that all 3 pages should be visible without scrolling. How can I achieve this? Here's a simple example I created on ...

Unable to retrieve the length of HTMLCollection

I've been having an issue with accessing all the dynamically created list elements (<li>) on my page using getElementsByTagName. The console keeps showing that the length of my li array is 0. Despite going through documentation and examples rel ...

Breaking down an array to create an object

When attempting array destructuring in JavaScript, I encountered some perplexing behavior. Below is the code snippet causing the issue: let result = { start: {}, end: {}, }; [result.start.hour, result.start.minute] = [7, ...

Ways to dynamically adjust the heading of the following page based on the preceding one

I am faced with a challenge involving two HTML pages. The first page features 3 tables containing people's names and last names, while the second page houses a single heading element. My goal is to enable users to click on a table on the first page an ...

React component not displaying dynamic image

I am currently working on a component that dynamically generates an image based on the passed prop. The component uses a switch statement to determine the correct path for the image source and stores it in the variable path. It seems like the issue lies wi ...

the current situation is that the nowjs initialize function is not working as

var express = require('express'); var app = express(); var nowjs = require('now'); app.get('/', function(req, res) { res.send('index'); }); var server = app.listen(4000); /* Setting up now.js to broadcast functio ...

Having trouble with Window.open on Mobile Devices and Canvas?

I've created a unique "button" within the div element. This button is designed to detect user interaction, such as clicks or taps, and when triggered, it should open a new window with the URL: "http://www.google.com". However, while this functionality ...

Challenges with downloading a file synchronously using NodeJS

Having trouble with writing files synchronously in my local application using the 'download-file-sync' module. When I use 'writeFileSync', the file size doubles even though the content seems to be identical to a file downloaded through ...

Encountering issues with running `npm start` following the creation of a fresh React project using create

Encountering an issue with react-scripts after setting up a new react project. I initiated the project using npx create-react-app dashboard. Upon entering the dashboard directory and executing npm start (without any prior actions), the following error is d ...

Error encountered in Angular 2 due to an unexpected token

After updating nodejs, I encountered an error with Angular 2 that was working fine before. Now, after updating the node_modules, it has stopped working and I am unsure of where the error is or how to fix it. (index):29 Error: (SystemJS) Unexpected token & ...

The click function operates only once

Here are two simple JavaScript functions: CTCC.Transactions.PieceRecuClick = function (source) { $(".chk input[type='checkbox']").attr('checked', true); } CTCC.Transactions.PieceNonRecuClick = function (source) { $(".chk input ...

Steps to ensure that ng-click event is not activated by elements within the container in AngularJS

Currently, I am facing the following scenario: <div ng-click="foo()"> <a ng-click="bar()">Bar</a> <p>Lorem Ipsun</p> </div> The issue at hand is that when I click on "Bar", both foo() and bar() functions are trigge ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...