In the case that all iterations come back empty, take a certain action, but if at least one of the iterations produces a result

I have a collection of values in an array that I need to iterate through to execute a function based on the input from a textbox.

Here's my code snippet:

<label for="truck">Truck:</label>
<input type="text" id="truck" name="truck">
<button type="button" id="myButton">Click Me!</button>

const truckBtn = document.getElementById("myButton");
const truckID = document.getElementById("truck");
truckBtn.addEventListener("click", () => {

  let arrs = ["one", "two", "three"];

  for (const arr of arrs) {
     axiosFunction(arr, truckID.value).then(d=> {
      console.log(d.data);
      if (d.data.length > 0) {
         // perform a task
      } else alert("Not Found");
   });
  }
});

In this scenario, d.data will be an empty array when truckID.value matches what is required:

[]
[]
[{...}]

This triggers the execution within the if statement.

The else block is activated when:

If truckID.value does not match the required criteria, resulting in a response of:

[]
[]
[]

The challenge arises when even with a successful match, it still enters the else block. Is there a way to formulate an if statement that checks if the length of the array is greater than 0 for at least one iteration? And how can we trigger the else condition only when all iterations return an array length of 0?

Answer №1

If possible, consider updating the API that powers your axiosFunction to handle all three arr values at once and return a batch result. However, if this is not feasible and you are willing to wait for all individual requests to complete (to ensure they don't return empty), you can leverage Promise.all() to synchronize their resolutions.

<label for="truck">Truck:</label>
<input type="text" id="truck" name="truck">
<button type="button" id="myButton">Click Me!</button>

truckBtn.addEventListener("click", () => {

  let arrs = ["one", "two", "three"];
  Promise.all(arrs.map(arr => axiosFunction(arr, truckID.value)))
    .then(results => {
      console.log(results.map(d => d.data)); // [[], [], [...]]
      const firstValidResult = results.find(d => d.data.length > 0);
      if(firstValidResult) {
         // do something with firstValidResult.data
      } else alert("Not Found");
    });
});

This implementation utilizes find under the assumption of a single valid result. If there could be multiple valid results, you might adjust it to use filter instead.

Answer №2

Transform the callback into an async function to utilize await. This will enable you to assign a variable based on whether any of the calls return a value.

button.addEventListener("click", async() => {
  let arrays = ["red", "blue", "green"];
  let isFound = false;
  for (const array of arrays) {
    let result = await fetchData(array, elementID.value);
    console.log(result.data);
    if (result.data.length > 0) {
      isFound = true;
      // perform actions
    }
  }
  if (!isFound) {
    console.log("No results found!");
  }
});

Answer №3

The method you choose for iterating through the array will impact your results - are you aiming to:

  • work with the first match exclusively, or
  • operate on every match found

To enhance your code snippet, consider using break once a match is located:

const truckBtn = document.getElementById("myButton");
const truckID = document.getElementById("truck");

truckBtn.addEventListener("click", () => {
  let arrs = ["one", "two", "three"];

  for (const arr of arrs) {
     axiosFunction(arr, truckID.value).then(d=> {
      console.log(d.data);
      if (d.data.length > 0) {
         // perform desired action
         break; // halt further iterations upon finding a match
      } else alert("Not Found");
   });
  }
});

Note the inclusion of break within the conditional statement to stop subsequent calls to axiosFunction. This might align with your intention or require adjustment.

Listed below are several approaches for handling these calls based on whether you wish to await each one, retrieve the initial matching outcome, or collect all matches, utilizing async / await and Array.map:

const arrs = ["one", "two", "three"];

// sequenced execution of axiosFunction calls, akin to a for loop
truckBtn.addEventListener("click", async () => {
  const matches = arrs.map(async x => await axiosFunction(x, truckID.value))
        .filter(x => x.data.length > 0);
  const match = matches.find(Boolean); // obtain the first truthy result

  // process non-null match accordingly
}


// simultaneous execution of all axiosFunction calls
truckBtn.addEventListener("click", async () => {
  const promises = arrs.map(x => axiosFunction(x, truckID.value));
  // fetch all matches
  const matches = await Promise.all(promises)
                    .filter(x => x.data.length > 0);
  const match = matches.find(Boolean); // obtain the first truthy result

  // process non-null match accordingly
}

// simultanous axiosFunction call execution, awaiting the first resolution
truckBtn.addEventListener("click", async () => {
  const promises = arrs.map(x => axiosFunction(x, truckID.value));
  const firstResolved = await Promise.race(promises);
  const match = firstResolved.data.length > 0 ? firstResolved : null;

  // handle match as required
});

// simultanous axiosFunction call execution, managing unresolved scenarios
truckBtn.addEventListener("click", async () => {
  const promises = arrs.map(x => axiosFunction(x, truckID.value));
  let match = null;

  try {
    const firstResolved = await Promise.any(promises);
    match = firstResolved.data.length > 0 ? firstResolved : match;
  } catch (err) {
    // no promise resolved
  }
  
  // process match accordingly
});

Answer №4

When utilizing the axiosFunction for multiple requests, it is essential to handle and resolve those promises by leveraging promises with methods such as Promise.allSettled() or Promise.all().

Subsequently, you can employ Array.prototype.some() or Array.prototype.every() to examine the returned data. In this case, nesting these methods may be required due to the nested array structure of the result.

Here's a demonstration using a simulated axiosFunction. Enter 'foo' in the input field for a specific outcome, or any other value for a "not found" message:

const searchButton = document.getElementById("searchButton");
const truckInput = document.getElementById("truckInput");

const items = ["one", "two", "three"];

function axiosFunction(array, value) {
  return Promise.resolve({
    data: value === 'foo' ? array.map((_, i) => [{}]) : array.map(_ => []),
  })
}

searchButton.addEventListener("click", async () => {
  const { value } = truckInput;
 
  // Initiate all requests concurrently:
  const promises = items.map((item) => {
    return axiosFunction(items, value)
  })
  
  // Ensure all requests are resolved:
  const results = await Promise.allSettled(promises);
  
  // Extract the data from the results:
  const resultsData = results.map(result => result.value.data);
  
  console.log(resultsData);
  
  // Iterate through each request's data:
  const found = resultsData.some((resultData) => {
    // Iterate over the items in the returned arrays:
    return resultData.some((resultItem) => {
      // Check if any item contains data:
      return resultItem.length > 0;
    });
  })
  
  if (found) {
    alert("Found!");
  } else {
    alert("Not Found...");
  }
});
<label for="truck">Truck:</label>
<input type="text" id="truckInput">
<button type="button" id="searchButton">Search</button>

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

Locate items that possess identical property values and append them to a new array as a property

I am dealing with an array containing objects that have a specific property called "operationGroup" with the sub-property "groupId". Here is an example of the array structure: [{ operation: 11111, operationGroup: null }, { operation: 22222, ...

Is there a way for me to retrieve a function from a different JavaScript file using jQuery?

Within the HTML, there exists a script referred to as Normal.js: $(function () { function WhiteNav() { $("#LOGO>img").attr('src', '/images/LOGOWhite.svg'); $("#NavUL a").css("color", "#cecece"); } }); ...

I am having difficulty accessing the environment variable stored in my Azure App Service configuration within my REACT application

After setting up my variable in the Azure app service configuration, I attempted to retrieve it from my React project. However, I consistently encountered an 'undefined' value. Azure App Service Configuration Link: https://i.sstatic.net/NextN.p ...

Creating Typescript packages that allow users to import the dist folder by using the package name

I am currently working on a TypeScript package that includes declarations to be imported and utilized by users. However, I have encountered an issue where upon publishing the package, it cannot be imported using the standard @scope/package-name format. I ...

Explore an array of objects to find and retrieve a value from the final matching object in JavaScript

I'm having difficulty retrieving the value for the last event that includes "SearchResults" in the scenario outlined below: Here is a schema of my datalayer where I am looking to gather information. Currently, I have managed to write the following co ...

Issue with scrolling when Bootstrap modal is opened on top of another modal

I recently created a modal using bootstrap, and inside this first modal, I added a button to open a second modal. Initially, everything worked perfectly fine. However, after closing the second modal, the scroll within the first modal stopped functioning pr ...

Using relative URLs, how can REST API be called within Node.js?

Within my express controller, the code is structured like so: const http = require('axios'); module.exports = { login: (req, res) => { res.render("admin/login.ejs", { errorMessage: req.flash('message')[0] }); ...

Navigating to a specific element with a smooth scroll in Angular after changing states

While working in Angular, I'm utilizing a node package to enable smooth scrolling on my website. One challenge I'm facing is implementing a feature where clicking on a link in the navbar while on a specific history state will take the user to tha ...

Is it feasible to cancel or clear the queue for a jQuery fadeOut function after a delay is specified? If so,

Can anyone help me out with this question? Is there a way to eliminate the delay in chaining? Mn.Base.TopBox.show = function(timedur){ $('#element').fadeIn().delay(timedur).fadeOut(); } Mn.Base.TopBox.cancelFadeout = function(){ } I&apos ...

Looping through items in a collection using Java: excluding a particular number

I'm working on an array and need a code snippet that will allow a for loop to run through a series of numbers, but skip a specific number when encountered. For example, if I want numbers 1 through 50 except for 22, how can I achieve that with a loop l ...

Encountering Angular Material UI issues following the transition from version 11 to 12

I am currently in the process of updating my Angular application from version 11 to 12, integrating Angular Material, and encountering some error messages: Error No.1 - Error NG8002: Cannot bind to 'ngModel' as it is not a recognized property of ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...

Malfunction occurs when selecting and deselecting options in a drop-down check box

I am using a DropDownCheckBoxes element <asp:DropDownCheckBoxes CssClass="FreeTextFilterSelection" ID="cbMarket" AddJQueryReference="false" UseSelectAllNode="True" AutoPostBack="true" DataTextField="Text" runat="server" OnSelectedIndexChanged="cb ...

Is the array being reset for no apparent cause?

Can you review this code for me? I am confused as to why it is showing [] at the last line. const arrcodces =[1,2,3,4] const arrOfPWs=[] const data=[] const arrOfPWs_2=[] const base=[ '2','3','4','5','6',&a ...

Non-IIFE Modules

Check out this discussion on Data dependency in module I have several modules in my application that rely on data retrieved from the server. Instead of implementing them as Immediately Invoked Function Expressions (IIFEs) like traditional module patterns ...

"Encountering unexpected issues while trying to find the second-largest element in the array

My algorithm to find the second smallest number is functioning correctly, but I am encountering issues with my code to identify the second largest number. I followed a similar approach for both functions, but it seems that the output for the second large ...

Can the loading of the window be postponed?

I've created a script that displays a message when the user first visits the website. The message then fades out, followed by another section fading in after a short delay. $(window).load(function() { $(".greeting").delay(1500).fadeOut("500"); ...

What is the purpose of using the http module to specify the port when the app.listen function already sets the

var express = require("express"); var app = express(); // This code sets the port to 8080 by default, or else it will use the environment-specific port. app.set('port', process.env.PORT || 8080); app.get('/', function(req, res){ r ...

"The use of objects as a React child is not permitted" and code linters

I'm encountering an issue with a simple component and I can't figure out why. The error message and code snippet are as follows: Error: Objects are not valid as a React child (found: object with keys {Cfor, children}). If you meant to render a ...

Is this a problem with npm or JavaScript?

Hi everyone, I'm trying to figure out if this issue is related to JavaScript or npm. If there's a problem with my JS code, could someone please help me identify it? PLEASE NOTE I used some code to get the current uid from Firebase. I'm ...