How to stop lodash.js _.each loop?

JavascriptLodash

Javascript Problem Overview


I have this rows code:

_.each($scope.inspectionReviews, function (value, key) {
    alert("status=" + value.IsNormal + "   " + "name=" + value.InspectionItemName);
    if (!value.IsNormal) {
        $scope.status = false;
        return;
    }
    $scope.status = true;
})

At some point I want to stop looping but it seems that return not working.

How can I stop the loop?

Javascript Solutions


Solution 1 - Javascript

return false;

Use this in a lodash each to break.

EDIT: I have seen the title changed to underscore. Is it underscore or lodash? As I pointed out above you can break an each in lodash but underscore I believe emulates forEach which natively doesn't provide that.

Solution 2 - Javascript

  • return false => it has exactly the same effect as using break;

  • return => this is the same as using continue;

Solution 3 - Javascript

If you want to test to see if a certain condition is true for any of the collection's members, use Underscore's some (aliased as any) instead of each.

var hasAtLeastOneFalseStatus = _.any($scope.inspectionReviews, function (value, key) {
    return !value.IsNormal;
})

$scope.status = hasAtLeastOneFalseStatus ? false: 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
QuestionMichaelView Question on Stackoverflow
Solution 1 - JavascriptAtheistP3aceView Answer on Stackoverflow
Solution 2 - Javascriptjack wuView Answer on Stackoverflow
Solution 3 - JavascriptncksllvnView Answer on Stackoverflow