From vanilla JavaScript to the powerful lodash library

Can you help me determine if these statements are equivalent?

myApp.filter('myFilter', function() {

  var result, i, sport, y, contains, league;
  return function(sports, filterBy) {    
    if (angular.isUndefined(sports) || !filterBy) {
      return sports;
    }

    filterBy = filterBy.toLowerCase();
    result = [],
    contains = function(haystack, needle) {
      return haystack.toLowerCase().indexOf(needle) > -1;
    };

    for (i = 0; i < sports.length; i++) {
      sport = sports[i];
      if (contains(sport.name, filterBy)) {
        result.push(sport);
        continue;
      } else {
        for (y = 0; y < sport.leagues.length; y++) {
          league = sport.leagues[y];
          if (contains(league.name, filterBy)) {
            result.push(sport);
            break;
          }
        }
      }
    }
    return result;
  };
});

Using lodash:

myApp.filter('myFilter', function() {

  var result, i, sport, y, contains, league;
  return function(sports, filterBy) {    
    if (angular.isUndefined(sports) || !filterBy) {
      return sports;
    }

    filterBy = filterBy.toLowerCase();
    result = [],
    contains = function(haystack, needle) {
      return haystack.toLowerCase().indexOf(needle) > -1;
    };

  _.each(sports.length, function(sport) {
      if (contains(sport.name, filterBy)) {
        result.push(sport);
        continue;
      } else {
        _.each(sport.leagues.length, function(league) {
          if(contains(league.name, filterBy)) {
            result.push(sport);
            break;
          }
        });
      }
    });

I'm trying to understand the logic behind using lodash. I have the same function in pure JavaScript, but when I try to convert it to lodash, my app stops working. Can you help me identify where I might be going wrong? You can check out the Plnkr with the pure JavaScript function in the library section where I've used underscore instead of lodash since lodash didn't load properly. My goal is to translate the function into a lodash function using _.each instead of a traditional for loop.

Answer №1

To handle this scenario, the use of "each" is not recommended. Additionally, with "each" you do not have the ability to "continue" or "break". In my opinion, utilizing "filter" would be more appropriate for obtaining a filtered result. Here is how the code should be structured:

var result = sports.filter(function(sport){
  return (
      contains(sport.name, filterBy) 
    || (
      sport.leagues && sport.leagues.some(function(league) { 
        return contains(league.name, filterBy) 
      })
    )
  )
})

Alternatively, for lodash/underscore:

var result = _.filter(sports, function(sport) {
  return (
      contains(sport.name, filterBy) 
    || (
      sport.leagues && _.some(sport.leagues, function(league) { 
        return contains(league.name, filterBy);
      })
    )
  )
});

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

Generating dynamic dropdown lists with JavaScript for variable arrays

I've been scouring the internet for quite some time now, both on this platform and through Google searches, but I can't seem to find what I'm looking for. (Apologies if I missed it and this comes across as a repetitive or annoying question.) ...

Utilizing Vue3's draggable component to seamlessly incorporate items

My current project involves the use of the vue draggable package, and below you will find the complete component: <template> <div> <button class="btn btn-secondary button" @click="add">Add</button> ...

Navigate through a series of div elements using Jquery

I need help figuring out how to make the window scroll between different divs in a sequence. The issue is that my current code only works for one specific div at a time. $('.down_arrow').click(function(e){ $('html, body') ...

Build a flexible Yup validation schema using JSON data

I am currently utilizing the power of Yup in conjunction with Formik within my react form setup. The fields within the form are dynamic, meaning their validations need to be dynamic as well. export const formData = [ { id: "name", label: "Full n ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

Reactjs, encountering a hitch in utilizing material UI: Incompatible hook call detected

As a newcomer to React, I decided to incorporate Material UI components into my project. After installing the components locally using npm install and importing them into my project, I encountered an error when trying to run start: Error: Invalid hook call ...

Randomly injecting strings like 'jQuery111201xxx' into a string using jQuery Ajax

After implementing a booking system that utilizes FullCalendar, I encountered an unusual issue with the 'notes' field. Occasionally, a strange string is inserted into the notes field at random points. Here's an example of what I found recent ...

The value for $routeParams.param appears to be undefined

I have set up a route and am attempting to send parameters to a controller: app.js .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('spot', { url: "/spot/:param", templateUrl: "templates/spot.html", ...

Flask - Refreshing Forms Dynamically

In an effort to enhance the responsiveness of my app, I am looking for a way to prevent the page from reloading every time a POST request is sent. My current setup includes a dynamically generated form with input fields designed like this: <div class=&q ...

Is there a way to prevent SignalR from disconnecting when the settings window is moved?

I am currently developing a webpage that utilizes SignalR events to trigger ajax requests to our servers. These requests return a URL with a custom URI scheme that, when accessed, opens up a specific program on the client's device without leaving the ...

Using AngularJS to integrate a function within a component

Hey there, I am facing an issue trying to call a function that is in a component. Let me share the code snippet from my component buttonsController: (function(){ "use strict"; angular .module('my') .component('myButton&ap ...

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Sending multiple arguments to a Vuex action

In the Vue Component code snippet below, I have a method: loadMaintenances (query = {}) { this.getContractorMaintenances(this.urlWithPage, query).then((response) => { this.lastPage = response.data.meta.last_page }) } I am trying to pass the par ...

Retrieving Files using Ajax Across Different File Types

I recently came across the following code snippet: DOM_imgDir = "img/UI/DOM/"; fileextension = ".jpg"; $.ajax({ url: DOM_imgDir, success: function (data) { $(data).find("a:contains(" + fileextension + ")").each(function () { filename = thi ...

Passing a function from one directive to another directive

I am facing a situation where I have two directives that are separate. If a certain condition is evaluated as true, I need to call the second directive from within the first one. myDirectives.directive('first', function() { return { restri ...

Changing the color of a specific span using Angular

I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header. ...

Animation for maximum height with transition from a set value to no maximum height

While experimenting with CSS-transitions, I encountered an unusual issue when adding a transition for max-height from a specific value (e.g. 14px) to none. Surprisingly, there is no animation at all; the hidden elements simply appear and disappear instant ...

The relationship between two distinct servers: Express.js and Node.js

Working with the Express.js framework and Node.js, I am trying to make a request to an MS SQL database on the server side. My goal is to retrieve data (in JSON or array format) from the server and send it to the client side. I'm unsure about how to ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

Managing the handling of each catch in $httpBackend.when()

I've been working on creating Jasmine unit tests for my Angular project, and I've come across a situation that I'm not quite sure how to tackle. Within my project, I have implemented a response interceptor that can retry a request if it enc ...