Utilize Lodash to iterate through functions in a loop and retrieve the first matching result

I am looking to iterate through an array of objects and call a method on them. If the result of that method meets certain conditions, I want to immediately return that result. The current implementation is as follows:

public getFirstMatch(value: string, allValues: string[]): Result {
    let foundResult = undefined;
    _.find(this.myArrayofMatchers, matcher => {
        let result = matcher.isMatch(value, allValues);
        if(result.isMatch){
            foundResult = result;
            return true;
        }
    })

    return foundResult || new Result(false);
}

While this code works, it feels clunky and unclear. Using _.find may not be the most intuitive choice, especially since the actual matcher itself is not important. Additionally, the need for foundResult variable seems unnecessary. Is there a more concise or efficient way to achieve this? Perhaps a different lodash function could help optimize this process?

As an alternative, I have also considered using a traditional for loop approach like below:

public isMatch(value: string, allValues: string[]): Result {
    for (let i = 0; i < this.myArrayofMatchers.length; i++){
        let result = this.myArrayofMatchers[i].isMatch(value, allValues);
        if (result.isMatch) {
            return result;
        }
    }
    return new Result(false);
}

Answer №1

Instead of using _.find in a way that resembles _.foreach, try optimizing your code. Lodash find returns a value, so make sure to make the most of it.

Consider updating your method to the following:

public retrieveFirstMatch(value: string, allValues: string[]): Result {
    const locatedResult = _.find(
        this.myArrayofMatchers,
        matcher => matcher.isMatch(value, allValues).isMatch
    );

    return locatedResult || new Result(false);
}

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

incapable of utilizing the $q library and promises

I am trying to make use of the variable StatusASof within the inserthtml function in the following manner. App.controller("SS_Ctrl", function ($scope, $http, $location, $window, $sce, $q) { var ShiftDetails = []; function acquireMAStatusASof(Id) { ...

How to retrieve values/keys from a JSON object dynamically in JavaScript without relying on fixed key names

shoppingCart = { "Items": 3, "Item": { "iPhone 11 Pro": { "productId": 788, "url": "http://website.com/phone_iphone11pro.html", "price": 999.99 }, "Bose Noise Cancelling Headphones": { ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

Tips on how to properly display the date in v-Calendar

I'm struggling to format the date output from the v-calendar. Currently, it appears like: Fri Jul 31 2020 00:00:00 GMT+0200 (utc summertime) However, I would like it to display as 2020-07-28. I have searched through the documentation but couldn' ...

Understanding the reading of Java Class List in Vue Js

As a beginner in Front-end development, I am trying to figure out how I can use Vue.js to read a Java class List. Specifically, I have a Java class that includes a list of fruits and I want to be able to display this list on the UI using Vue.js: public c ...

Tips for monitoring multiple values in a Vue 3 script setup

Within my code, I currently have a watcher set up like this (inside <script setup>): const form = reactive({ body: '', image: '' }) watch(() => form.image, () => { console.log(form.image) }) I am looking to enh ...

What are some of the methods that can be used with the Facebook API to interact with the Like button

I am working on developing a JavaScript script that will automatically click on all the LIKE buttons for posts loaded on Facebook in the Chrome browser. Input: "" Or any other FB page,Groups,Profiles Step1: I will scroll down to load all the posts S ...

Typescript: requirement appears to be unmet

While compiling my Angular project, I encountered an error related to a package installed via NPM: node_modules/astrocite-ris/index.d.ts:36:39 - error TS2503: Cannot find namespace 'CSL'. The package named Astrocite contains a subpackage calle ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

Is it necessary to integrate the Facebook JavaScript SDK even if I do not plan on utilizing its features?

I have created some simple applications to use as custom tabs on my Facebook page, consisting of hyperlink images. I am not utilizing any of the functionality provided by the Facebook JavaScript SDK in these instances. Do I really need to load the Faceboo ...

Leverage predefined JavaScript functions within an Angular template

I have been attempting to execute an eval function within my angular template in the following manner: <div *ngFor="..."> <div *ngIf="eval('...')"></div> </div> You understand what I'm trying to ...

Fetch several images simultaneously from a photo collection using JavaScript by generating a batch process

I need help with creating an image gallery that allows users to download multiple images by selecting them. The download should result in a zip file. I have checkboxes for selecting the images, but I'm struggling to figure out how to enable the downlo ...

Issue with tsconfig compilerOptions "module": "system" not functioning as expected

During my journey with the Angular2 5-minute tutorial, I encountered an issue with the "system" module in the tsconfig file. Despite having systemjs as a node_module, I faced an error message saying System is not defined at the beginning of the compiled js ...

Creating a collapsible accordion feature with jQuery using a specific HTML layout: wanna learn how?

I am looking to create an accordion effect with the structure provided below. The goal is to have the corresponding article toggle when clicking on .booklist>li>a, allowing only one article to be open at a time. Can someone assist me with writing thi ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

How can we convert a mixed-case word into one or more words with initial capital letters?

Is there a way to convert caps and spaces to their normal form? For instance, can the word coreControllerC4a be transformed into Core Controller C4a automatically when a function is triggered? ...

Error in Node.js: Trying to access property 'get' of an undefined object

Although I have some knowledge of JavaScript, I am new to Node.js. Despite it being a common issue, I am having trouble identifying the source of the error because my debugging skills in Node.js are lacking. Here is my app.js: var index = require('. ...

Struggling with object type casting in Typescript

Having issues with casting objects from an HTTP API response to Typescript. I am trying to cast the json data to a Typescript object using the "as" keyword or <Type >, but it's not working as expected. r.forEach(entry => { entry.creatio ...

Does the color of the item change as it gets older?

How can I smoothly transition a color as it ages using a dynamic time scale? I want to calculate the age based on the difference in time rather than triggering an animation after an event. I aim for a seamless gradient transition between two colors over a ...

Error: The module 'https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js' is missing the required export 'default'

I'm currently in the process of setting up and testing Google authentication for a web application that I'm developing. Unfortunately, I've encountered several issues with getting the JavaScript functions to work properly, and I am uncertain ...