Is there a way to stop a for-in loop within a nested forEach function in JavaScript?

I am facing a situation with nested loops

for (var key in params) {
  if (Array.isArray(params[key])) {
    params[key].every(function(item) {
      let value = something(item.start, item.end);
      if (value === item.start || value == item.end) {
        return false // break
      }
    })
  }
}

When I use return false to stop the inner every() function, I also want to end the outer loop. How can I achieve this? I attempted the following:

OUTER_LOOP: for (var key in params) {
  if (Array.isArray(params[key])) {
    params[key].every(function(item) {
      let value = something(item.start, item.end);
      if (value === item.start || value == item.end) {
        return false // break
        break OUTER_LOOP; // not working
      }
    })
  }
}

However, this approach does not work as expected...so how can I correctly stop both the every() function and the outer loop simultaneously?

Answer №1

To efficiently break out of a loop after meeting a certain condition, you can utilize the Array#some method. With this approach, you return true within some to exit the loop based on specific criteria.

for (var key in params) {
    if (Array.isArray(params[key])) {
        const
            leave = params[key].some(item => {
                let value = something(item.start, item.end);

                // To break the outer loop, the exit condition must evaluate to true/truthy
                return value === item.start || value == item.end;
            });

        if (leave) break;
    }
}

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 rendering JSON encoded data in a JqPlot Chart within a PHP script

I've spent the past few days scouring through Stack Overflow and various other websites, but I haven't been able to find a solution to my specific issue. Even the book 'Create Web Charts with JqPlot' by Fabio Nelli didn't provide t ...

What is the best way to trigger a javascript modal to open automatically after a specific duration

Let's take an instance where my modal has the ID #modal1. It usually appears through a button-based action. ...

Utilize MaterialUI's stepper component to jazz up your design with

Is there a way to customize the color of a material ui Stepper? By default, the material UI stepper's icons use the primary color for both "active" and "completed" steps. class HorizontalLinearStepper extends React.Component { state = { activeS ...

Retrieving data from Immediately Invoked Function Expressions

I've been working with a closure that looks like this: var Container = (function () { var variable; var changeVariable = function () { variable = 5; }; return { variable: variable, changeVariable: changeVariable }; ...

Version 5 of Material UI has a bug where the Grid component does not properly stretch

How can I make the Grid component stretch when one of the Card components contains extra text? You can view the sample code here. Changing the alignItems property to "flex-end" or "center" works, but when using alignItems: "stretch" it does not work. I ...

Guide on resolving a "res is not defined" issue in Node.js

I've been struggling to test the controller logic for a user validation module, but I keep encountering an error that says "res is not defined" even after trying to define it. How can I properly define it so that it runs through the condition statemen ...

Can a "fragile export" be generated in TypeScript?

Testing modular code can be challenging when you have to export things just for the purpose of testing, which can clutter your code and diminish the effectiveness of features like "unused variable" flags on compilers or linters. Even if you remove a usage ...

How do I rearrange the order of a collection in Firestore using a reference that I already have?

Is there a method to maintain a reference of the same collection while altering the ordering using firestore? TLDR: I am looking to achieve similar functionality as demonstrated in: , but since my data is sourced from firestore, I am struggling to find th ...

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

Refresh Layers in Openlayers with LayerRedraw(), Rotate Features, and Manipulate Linestring Coordinates

TLDR: I am facing difficulties with my OpenLayers map. Specifically, I want to remove and add a layer called 'track', or find a way to plot a triangle based on one set of coordinates and a heading (see below). In my OpenLayers map, there is an i ...

What is the best way to retrieve my data/json from req.body in Express?

Recently, I started working with node.js and encountered an issue while trying to access JSON data on my node.js server through a post request. The goal is to send this data to an API and then pass it back to my front-end JavaScript file. Despite being abl ...

"Is there a way to retrieve a field from a different model within a Mongoose model

Presented below are two distinct MongoDB Models: Movie Model import mongoose from 'mongoose'; const movieSchema = new mongoose.Schema({ title: { type: String, required: [true, 'Please Enter the Movie Title'], trim: true, ...

Concealing and revealing the triangular indicator within a bullet diagram using the AngularJS-nvd3-directives library

I am currently utilizing the nvd3-bullet-chart feature from the angularjs-nvd3-directives library in order to present maximum, current, and average data. To exclude the minimum variable from the array for display purposes, I have set its value to 0. In a ...

Limit the input to numbers when pasting into Angular

Implementing a directive in <input type='text'> to restrict user input to numbers has been successful! The issue arises when a user copies and pastes a string, causing Angular to accept the value and send it to the backend. angular.module ...

Unexpected obstacles encountered when implementing the jqTouch JavaScript/AJAX combination on Android

In jqtouch, I'm using vanilla ajax calls to load multiple pages: <li class="arrow"><a href="folder/another/somepage.html" >BRAVIA HDTVs</a><small class="counter">2</small></li></li> I want to incorporate a v ...

Ways to Toggle div Visibility for Elements with Identical Class Names on an Individual Basis

After searching for solutions on stackoverflow, I attempted to implement some answers provided by other users, but I'm still not achieving the desired outcome. In my website's about section, there are four different items. When a specific item&a ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

Fetch response headers not being detected by Web Worker

Currently in my chrome extension, I'm utilizing web workers to collect response header cookies from a specific website. Interestingly, when I execute the request on the main thread, the response contains all the expected cookies. However, when the exa ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

Parsing XML to JSON using JavaScript

I came across this JavaScript function on Stack Overflow that I've been using to convert XML to JSON: function xmlToJson(xml) { try { var obj = {}; if (xml.nodeType == 1) { if (xml.attributes.length > 0) { ...