John Smith John Smith - 19 days ago 5
Javascript Question

Stop function if condition is true

I use the Array

map()
Method to check each element in an Array and if the condition in the if clausel is true i call another function.

$.map(data['icd'], function (field, i) {
if(field.nummer == search){
Diagnose.single(field.id);
};
});


Now my problem is that i want to stop the
map
method if a element fullfills the if condition. Because i noticed that when i have for example 6 elements that fullfill the condition the function
Diagnose.single(field.id);
is called 6 times instead of once!

I tried:

$.map(data['icd'], function (field, i) {
if(field.nummer == search){
Diagnose.single(field.id);
return true;
};
});


But this didnt worked! What can i do instead? Thanks

Answer

Use simple for-loop with break statement:

for (var i = 0; i < data['icd'].length; i++) {
   if (data['icd'][i].nummer == search){
      Diagnose.single(data['icd'][i].id);
      break;
   };    
}

map is used for different tasks.