Reputation: 1643
I want to do the simple yet need the fastest way of doing so in javascript:
I have this array :
players: [{
isInjured : false,
name: ...
stamina : 50
},{
isInjured : true,
name: ...,
stamina : 20
}
...
]
I have 2 things i want to do in the best, fastest way possible:
1)If i have in the array a true in the "inInjured" Property, to anyone.
2) i want to extract the 3 lowest stamina players, and extract the key of one of those.
I want to avoid, if possible, from doing 2 forEach for this, so what is the best way?
Upvotes: 0
Views: 56
Reputation: 11234
var players = [{
isInjured: false,
stamina: 50
}, {
isInjured: false,
stamina: 10
}, {
isInjured: false,
stamina: 15
}, {
isInjured: false,
stamina: 16
}, {
isInjured: true,
stamina: 20
}];
// Your second request you can do with lodash or underscore easily
var threePlayersWithMinStamina = _.take(_.sortBy(players, function(player) {
return player.stamina;
}), 3);
console.log(threePlayersWithMinStamina) // you have the three players with the min stamina
//Your first request
// the var isOneInjured will be true if the condition will be true and stop the loop
var isOneInjured = players.some(function(player) {
return player.isInjured;
});
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>
Upvotes: 2
Reputation: 25892
Use Array native some function like bellow
var isSomeoneInjurd = players.some(function(pl){
return pl.isInjured;
});
The value of isSomeoneInjurd
will be true if any of player has property isInjured
as true. And it will break the loop as soon as it gets one true for that property.
Upvotes: 1