How to stop running $.map?

Asked

Viewed 1,146 times

2

How do I stop function execution $.map when a condition of if is true?

With for I would wear a break thus:

for (int i = 0; i < count; i++){
    if (true)
        break;
}

And in function $.map jquery, as it would be?

  • 1

    What is the goal? Maybe map is not the proper function, because it is made to transform all the values of the array.

3 answers

3

You cannot "break" the execution of the map function. I recommend taking a look at the function $.each.

  • the $each I get for execution?

  • Yes, returning false of the function passed to it. But it would be nice to further clarify its objective with the question, maybe there is some better solution. And for common you can also use and give break, exactly as in C#.

3


You can create your own mapping function if jQuery’s does not solve you.

var stoppableMap = function (inputArray, mainFunction, haltFunction) {
    var result = [];
    for (var i = 0; i < inputArray.length; i++) {
        if (haltFunction(result, inputArray[i], i) === false) {
            break;
        }
        result.push(mainFunction(inputArray[i], i));
    }
    return result;
}

What happens here is the following: you call the above function by passing a vector as input and a function that receives index and element, similar to what you would do with the function $.map..

For each vector element, the function passed as the parameter mainFunction will be executed once. the first parameter it receives is current element, and the second parameter is the index of the current element.

The difference is in the function passed as the third parameter, haltFunction. It is also executed for each element of the original vector, but before the mainFunction. It takes three parameters: the vector resulting from the mapping so far, the current element and the index of the current element. If it returns false (explicit - "", 0, null and undefined do not serve), the loop of the mapping function is interrupted. CQD.

You can modify the function at will: make the stop function run after and not before the main function, pass an extra parameter to have more context or whatever your logic needs.

Note that this function is much simpler than the $.map. It neither iterates over objects nor flattens vectors at every turn of the main function you pass. You can implement these details if necessary.

Example of use, for when you find a value element 3:

stoppableMap([1, 2, 3, 4, "a Maria é um barato"],
        function (elem) {
            return "elemento de valor " + elem;
        },
        function (accumulate, elem) {
            if (elem == 3) return false;
        });

Good luck ;)

2

Unable to interrupt the flow of jQuery.map() in itself because its purpose is to be applied to all elements of the given array. But it is possible to do its callback ignore certain iteration values, not applying to them according to some condition.

Routines of Mapping in the vast majority of times aim, as its name suggests, to map the elements of an array from something to something else. If an element should not be mapped, just return the element itself:

var arr = [ "a", "b", "c", "d", "e" ];
 
arr = jQuery.map( arr, function( n, i ) {
  if ( i == 2 ) { return n; }
  return ( n.toUpperCase() );
});

console.log( arr );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Looking at the console we will see that all elements of the past array have been mapped to uppercase letters, except the third index that has been kept unchanged.

It is also possible, although wrong, to use jQuery.map() as an alternative to jQuery.each(), running something for each element of the input array without, in fact, turning it into nothing.

For these cases, instead of returning the current value, a return false allows you to "skip" the current iteration when any condition is met.

$.map( [ 'one', 'two', 'three', 'four' ], function( val, i ) {
  
    if( i > 2 ) return false;
    
    alert( val );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In this example I check the current iteration index. If it is greater than 2 I close the iteration and, consequently, the input four is not shown in Alert().

  • Thanks for the two feet on the chest without a single comment. It seems that cheating is prohibited...

  • Passing by and saw your comment, I thank you for the answer. I’m sorry ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.