How to stop a JavaScript for loop?

JavascriptFor Loop

Javascript Problem Overview


I'm using this JavaScript to iterate through an array and find a matching array element:

var remSize = [], 
    szString, remData, remIndex, i;

for (i = 0; i < remSize.length; i++) {		
    // I'm looking for the index i, when the condition is true
    remSize[i].size == remData.size ? remIndex = i : remIndex = -1;		
}

The array contains these "sizes": ["34", "36", "38"...].

remData.size is the "size" I'm looking for (e.g. "36").

I need to return the index i if the size I'm searching for is in the index. Otherwise I need to return -1. Is there a better way to do this?

Javascript Solutions


Solution 1 - Javascript

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
    szString,
    remData,
    remIndex,
    i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {      
     // I'm looking for the index i, when the condition is true
     if (remSize[i].size === remData.size) {
          remIndex = i;
          break;       // <=== breaks out of the loop early
     }
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array's findIndex (to find the entry's index) or find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
     return entry.size === remData.size;
});

find stops the first time the callback returns a truthy value, returning the element that the callback returned the truthy value for (returns undefined if the callback never returns a truthy value):

var remSize = [], 
    szString,
    remData,
    remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
     return entry.size === remData.size;
});

findIndex stops the first time the callback returns a truthy value, returning the index of the element instead of the element; it returns -1 if the callback never returns a truthy value.

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
    if (entry.size === remData.size) {
        remIndex = index;
        return false; // <== Equivalent of break for jQuery.each
    }
});

Solution 2 - Javascript

Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/

let arr = [1,2,3,4,5];
for (let ele of arr) {
  if (ele > 3) break;
  console.log(ele);
}

Solution 3 - Javascript

The logic is incorrect. It would always return the result of last element in the array.

remIndex = -1;

for (i = 0; i < remSize.length; i++) {      
    if (remSize[i].size == remData.size) {
        remIndex = i
        break;
    }
}

Solution 4 - Javascript

I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])

It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.

<array> is the array to look through, <element> is the value you are looking for, and [fromIndex] is the index to start from (defaults to 0).

I hope this helps reduce the size of your code!

Solution 5 - Javascript

It is also possible to use every method of Javascript. It would stop the execution when condition is not true.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

remIndex = -1;

remSize.every((rem, index) => {
  if (rem.size == remData.size) {
        remIndex = i
        return false
  }
  return true
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfrequentView Question on Stackoverflow
Solution 1 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 2 - JavascriptSrini KarthikeyanView Answer on Stackoverflow
Solution 3 - Javascriptamit_gView Answer on Stackoverflow
Solution 4 - JavascriptJMoore2007View Answer on Stackoverflow
Solution 5 - JavascriptKuldeep SaxenaView Answer on Stackoverflow