Script to find actor with lowest health

Hey guys,

would anyone be so kind to write me a script (preferably with step by step explanation on what line does what) that finds an actor with lowest (current) HP? I'm trying to make a skill that as a secondary effect heals the weakest party member.

Thank you in advance 🙂
Code:
var index = null; for (var i in $gameParty.members()) if ($gameParty.members()[i].hp < $gameParty.members()[index].hp) index = i; $gameParty.members()[index].gainHp(hp);
Thank you @Poryg

Unfortunately the script you posted doesn't work for me. Perhaps I should've mentioned that I'm using Yanfly's engine and I want to run the script via skill's Note box.
Code:
$gameParty.members().reduce((lowestMember, member) => member.hp < lowestMember.hp ? member : lowestMember);

Syntax only works with MV 1.6 or above, but can be slightly modified to work with older versions:
Code:
$gameParty.members().reduce(function(lowestMember, member) { return member.hp < lowestMember.hp ? member : lowestMember });

The reduce method can be called on any Array. You pass in a function that accepts two parameters which will be called on every element in the Array. The first is an accumulator, the second is the current element in the Array. Whatever the function returns becomes the accumulator. When all elements have been iterated on, the accumulator is returned.

If you don't provide an accumulator as a second argument, along with your function, then the accumulator starts as the first element in the Array.

Since we don't provide one, the accumulator will start as the first party member. Then, for each subsequent member, if they have less HP than the current accumulator (lowestMember), that member is returned and thus becomes the accumulator. Otherwise, the current accumulator is returned.

The result of the code is the lowest-health member. I don't know how Yanfly's noteboxes work, so you'll have to figure out how to assign that value somehow.
Thank you @Zevia

The method you described works perfectly.

This thread is being closed, due to being solved. If for some reason you would like this thread re-opened, please report this post and leave a message why. Thank you.

Original thread: https://forums.rpgmakerweb.com/threads/script-to-find-actor-with-lowest-health.111998/