underscore's _.each() method for callback functions

I've been struggling with implementing my custom _.each() function within another function and keep encountering the issue of getting "undefined" returned. My goal is to utilize _.each() to apply a test function to an array. Despite being aware that this is likely a simple callback syntax problem, it continues to perplex me.

Any help would be greatly appreciated by this newbie.

Below is the function in question:

_.filter = function(collection, test) {
  _.each(collection, test());
};

The result of this is 'undefined'

This is the array I'm passing as 'collection':

[1, 2, 3, 4, 5, 6] 

And here's the function I'm passing as 'test':

function (num) { return num % 2 !== 0; } 

Here's how my _.each() function looks:

_.each = function(collection, iterator) {

    if( Object.prototype.toString.call( collection ) === '[object Array]' ) {
        for (var i=0; i<collection.length; i++){
            iterator(collection[i], i, collection);
        }
    } else if (typeof collection === 'object'){
        for (var i in collection){
            iterator(collection[i], i, collection)
        }
    } else if (typeof collection === 'int'){
        console.log('int')
    }
};

Answer №1

 _.filter = function(collection, test) {
  var filteredItems =[];
  _.each(collection, function(item) { 
    if (test(item)) 
    filteredItems.push(item);
  });
  return filteredItems;
};

Issue resolved successfully!

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

Having trouble getting my parallax slideshow to work with jquery preventDefault

-UPDATE- After countless hours of online courses, tutorials, and programming, I finally completed my website! Check it out here: The site is almost where I want it to be, but there are a few remaining challenges: 1) AJAX: I'm struggling to get the ...

What could be causing XMLHttpRequest to encounter issues with the readystate and status states while running on localhost

Hey guys, I'm having some trouble with this code and can't figure out why it's not working. Here is the code snippet: <script> function findMatch() { if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...

Unable to open new tab using target _blank in React js production build

After attempting to access the link, a 404 error appeared in the live version of react js and triggered an error on the firebase hosting platform. <Link target='_blank' to={'/property-details?id='some_id'}/> ...

The API request is experiencing delays due to the large dataset of 250,000 records

Utilizing API calls to retrieve data for the frontend is essential, but with a database table containing 250,000 rows, efficiency becomes a concern. In my .NET Core application, I implement the following query: IQueryable<Message> query = context.Me ...

Is there a way to maintain scroll position on a dynamically refreshing div?

After searching for hours, I still can't find a solution to my problem. I am using a simple JQuery script to refresh a div and display my PHP output in it. $script = " <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery ...

JavaScript redirecting without refreshing the page

Currently, I am faced with a dilemma involving an Ajax function that calls a remote site, saves data to a database, and then needs to refresh the current page to display the new information. The complication arises from the fact that tabs are being utilize ...

Storing the value from the INPUT field in the state of React is not permitted

I'm attempting to retrieve the user input value from the INPUT field and update it in the corresponding state. However, no matter what I type in the field, it doesn't get set to the state. createForm(x){ var dx = 'd'+x let da ...

Struggling with sending intricate model to controller via ajax request

I've encountered an issue where my model is not updating properly when I click a button. Despite logging the data in the razor file and confirming that it's correct, the controller method receives an empty model. Below is the onclick method bein ...

Error encountered while trying to retrieve JSON data

After running the following code, I encountered an issue I received an error message stating: Uncaught TypeError: Cannot read property 'searchname' of undefined What could be causing this error and how can I fix it? var selectedVal = "calend ...

display PHP JSON information using jQuery AJAX

I'm completely new to this subject. I have a Json result that looks like the following : { "span": " 1", "numcard": "12", "chan": " Yes", "idle": "Yes", "level": "idle ", "call": "No ", "name": "" } My goal is to ...

What is the proper way to utilize document.getElementById() within a standalone js file?

As I dive into learning web development for the first time, I've decided to keep my scripts organized in separate files. However, I'm facing a challenge when trying to access elements from these external files. Below is a snippet of the JavaScri ...

What is the best way to remove text messages from a channel that only allows images?

I have developed a Discord bot named YES with a specific text channel for images only. My goal is to program the bot to automatically delete any text messages in this channel and respond with "You cannot send text messages." However, I also want to create ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...

Ways to programmatically append data to an object using JavaScript

My dilemma involves an object: var myObject={}; accompanied by a function that appends values to the object: function appendData(id, name){ //logic to validate id and name format, specify conditions for name being "John" and id being "I23423" my ...

Having trouble implementing table row selection with semantic-ui table

I am currently in the process of adopting Semantic-UI, but I am encountering some issues. Specifically, I am struggling to make row selection work in a table. Below is the sample HTML I am using from Semantic-UI: <table class="ui selectable celled tab ...

What is the best way to add child elements to existing elements?

When it comes to creating elements with jQuery, most of us are familiar with the standard method: jQuery('<div/>', { id: 'foo', href: 'http://google.com', }).appendTo('#mySelector'); However, there ar ...

Having trouble with object initialization in a jQuery GET request?

Looking to create an HTML button using jQuery that, upon clicking the chart button, will retrieve values from specified text inputs. These values will then be used to construct a JSON object which will subsequently be included in a GET request. $(".chart" ...

Using JavaScript: How to utilize Array.reduce within a function that also accepts arguments

let foo = 0; let bar = 0; const arr1 = [1, 2, 3, 4, 5]; const arr2 = [6, 7, 8, 9, 10]; function calculateSum(arr) { return arr.reduce((accum, val) => accum + val, 0); } foo = calculateSum(arr1); // Expect foo to equal 15 bar = calculateSum(arr2); ...

Exploring the World of Subclassing Arrays in JavaScript: Uncovering the TypeError of Array.prototype.toString's

Can JavaScript Arrays be subclassed and inherited from? I am interested in creating my own custom Array object that not only has all the features of a regular Array but also contains additional properties. My intention is to use myobj instanceof CustomArr ...