Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

Brittle Morale; Kills but No Success?

I’ve been stuck on this one for pushing a month (though, I’ve been away a good bit…).

Looked at other posts, and have been redoing old levels to better understand arrays, etc. My hero kills the leader, but then everyone attacks and we die.

// You have one arrow. Make it count!

// This should return the enemy with the most health.
function findStrongestEnemy(enemies) {
    var strongest = null;
    var strongestHealth = 0;
    var enemyIndex = 0;
    // While enemyIndex is less than the length of enemies:
    while(enemyIndex < enemies.length) {

        // Set an enemy variable to enemies[enemyIndex]
        var enemy = enemies[enemyIndex];
        // If enemy.health is greater than strongestHealth
        if (enemy.health > strongestHealth) {
            
            // Set `strongest` to enemy
            // Set strongestHealth to enemy.health
            strongest = enemy;
            strongestHealth = enemy.health;
        // Increment enemyIndex
        }
        enemyIndex += 1;
    
    return strongest;
        }
    }

var enemies = hero.findEnemies();
var leader = findStrongestEnemy(enemies);
if (leader) {
    hero.say(findStrongestEnemy(enemies));
}

Thanks in advance for the help.

Hi bobmcphe!
The function’ll always give the first enemy in the array, because you return while iterating through every enemy.
What you want to do, however, is to return strongest AFTER you’ve checked every enemy, not during the check! Hope this helps :sweat_smile:

That did it, thank you.