0

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

John Smith
  • 6,105
  • 16
  • 58
  • 109

4 Answers4

6

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
4

If you do not need IE8 support, you can use Array.prototype.some

data['icd'].some(function (field, i) {
   if(field.nummer == search){
      Diagnose.single(field.id);
      return true;
   };
});
PanJ
  • 68
  • 5
1

Return false and replace .map with .each

$.each(data['icd'], function (field, i) {
   if(field.nummer == search){
      Diagnose.single(field.id);
      // Need to return false, return true will go for a success and still continue.
      return false;
   };
});
ReGdYN
  • 536
  • 2
  • 7
  • I don't think this works... in [the docs](http://api.jquery.com/jQuery.map/) for map, it states: The function can return: 1) the translated value, which will be mapped to the resulting array. 2) null or undefined, to remove the item. 3) an array of values, which will be flattened into the full array. – Mottie May 10 '14 at 15:39
  • Sorry, you also have to replace .map with .each, I already edited my initial answer. – ReGdYN May 10 '14 at 15:40
1

I think in your case you want to use the jQuery each function. You can then return false to break out of the loop

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

or even better, use a simple for-loop as @disq shared.

Mottie
  • 84,355
  • 30
  • 126
  • 241