Reputation: 6259
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
Upvotes: 0
Views: 19252
Reputation: 78
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;
};
});
Upvotes: 4
Reputation: 86413
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.
Upvotes: 1
Reputation: 536
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;
};
});
Upvotes: 1
Reputation: 193261
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.
Upvotes: 6