How to stop execution of the $ .map function?

2

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

With for I would use a break like this:

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

And in the $.map function of Jquery, what would it be like?

    
asked by anonymous 11.11.2014 / 14:53

3 answers

3

You can create your own mapping function if jQuery does not resolve it.

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 this: you call the above function by passing a vector as input and a function that receives index and element, similarly to what you would do with the function $.map. .

For each vector element, the function passed as the mainFunction parameter will be executed once. the first parameter it receives is the 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 mainFunction . It receives three parameters: the resultant vector of 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 work), the mapping function loop is interrupted. CQD.

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

Note that this function is much simpler than $.map . It does not iterate over objects or flatten vectors every round of the main function you pass. You can implement these details if necessary.

Use example, which for when it finds an element of value 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;)

    
11.11.2014 / 16:56
3

You can not "break" the map function. I recommend taking a look at $ .each .

    
11.11.2014 / 15:01
2

Can not stop the flow from jQuery.map () itself its purpose is to be applied to all elements of the given array. But it is possible to make your callback ignore certain values of the iteration, not applying to them according to some condition.

mapping routines most often aim, as the name suggests, to map the elements of an array of something to something else. If any 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>

Lookingattheconsolewewillseethatalltheelementsofthelastarrayweremappedtouppercaselettersexceptthethirdindexthatwaskeptunchanged.

Youcanalsouse jQuery.map () as an alternative to jQuery.each () , executing something for each element of the input array without actually transforming it into anything.

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

$.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 index of the iteration. If it is greater than 2 I terminate the iteration and consequently the four entry is not shown in alert ().

    
11.11.2014 / 15:31