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?