Hello, sports fans! Ahead of the next issues of Slip into Ruby and Jump into JavaScript, I'd like to cover a couple of functions that I consider an absolute godsend to the language (which are also available in Ruby for the VX Ace users) which make some seemingly-complex operations an absolute breeze. I am talking, as the title suggests, about .map and .reduce, which are two functions inherent to Array.prototype. Meaning that any array can call them.
But babbling on about the ins and outs of the language isn't going to help people who aren't coders, so let's create something useful: an example! One that I'm sure many of you will find a use for somewhere. We're going to calculate the average agility of all our party members.
So let's consider how one calculates an average: you add up the total of all contributing values, then divide by how many values there are. If you have 6 people of ages 21, 56, 78, 19 and 22, to average them you'd add up the ages (196) and divide by the number of people (6), or 196 / 6, giving an average age of 32.66 repeating.
Now let's look at how we access party member information. We have a variable, $gameParty, which has a members() function which returns an array of every party member. Now, the "most basic" way to do this is:
And that would be a perfectly serviceable solution, with a few problems. The first and most glaring is that it only works if we have four party members; any fewer and we get an error, any more and the average will be off. So let's use a for loop instead:
And that's a bit better, but JS has a couple of functions that make this a bit easier and cooler. First of all, let's eliminate the issue that the array we're dealing with is an array of Game_Actor objects. What we *want* is an array of agi values, and that's where map comes in.
To put it simply, map is a function you call on an array which takes each element of that array and performs a particular piece of code on it, which you supply to it. It then returns a new array where each element is the result of performing that code. So if our party members have an agi value of 10, 12, 10 and 15 respectively...
Will return [10, 12, 10, 15].
The "member" after the first bracket is just the name we're giving to the current element of the array. We could have called it almost literally anything. I could have called it "banana" and done "banana.agi" but I like to give my iteration variables meaningful names. 😛
So, great! We now have an array of numbers. So we could do
And that's a huge improvement! We only have one call to $gameParty.members() in the whole thing, so we're eliminating some unnecessary function calls. But it still has the same need for a totalAgi variable and a for loop and it just seems like it should be a bit easier, y'know? And that's where we couple our map with the very powerful reduce.
Reduce is a function which, again, is called on an array. It takes two parameters rather than map's one: one for the current element, and one that holds a value which persists throughout all iterations. Or for our purposes, the total. To wit:
[1, 5, 7, 10].reduce((total, value) => total + value);
Will return 23. You can already see where I'm going with this:
And presto, we've reduced (lol) 5-6 lines of code down to 3. But it gets even better, because in JS you can chain function calls:
So we can do all that in a single line of code! This way does need another call to $gameParty.members() to get the number of elements, but I think you'll agree it's a lot more compact.
These aren't the only ways to use map effectively either. Let's say you have an array of strings and want to convert them to lowercase for comparing with specific words/phrases:
lcStrings will return ["this", "is", "a", "string", "array"] and you can now compare the values without caring how they were passed in the first place.
Array has some other cool functions as well, but these two are my favourites and used together they can be incredibly powerful. Hope this was helpful!
Edit: Thanks to @Solar_Flare for also pointing out that this can be done with just reduce:
But babbling on about the ins and outs of the language isn't going to help people who aren't coders, so let's create something useful: an example! One that I'm sure many of you will find a use for somewhere. We're going to calculate the average agility of all our party members.
So let's consider how one calculates an average: you add up the total of all contributing values, then divide by how many values there are. If you have 6 people of ages 21, 56, 78, 19 and 22, to average them you'd add up the ages (196) and divide by the number of people (6), or 196 / 6, giving an average age of 32.66 repeating.
Now let's look at how we access party member information. We have a variable, $gameParty, which has a members() function which returns an array of every party member. Now, the "most basic" way to do this is:
Code:
let member1 = $gameParty.members()[0];
let member2 = $gameParty.members()[1];
let member3 = $gameParty.members()[2];
let member4 = $gameParty.members()[3];
let avgAgi = (member1.agi + member2.agi + member3.agi + member4.agi) / 4;
return avgAgi;
And that would be a perfectly serviceable solution, with a few problems. The first and most glaring is that it only works if we have four party members; any fewer and we get an error, any more and the average will be off. So let's use a for loop instead:
Code:
let totalAgi = 0;
for (var i = 0; i < $gameParty.members().length; i++) {
let member = $gameParty.members()[i];
totalAgi += member.agi;
}
let avgAgi = totalAgi / $gameParty.members().length;
And that's a bit better, but JS has a couple of functions that make this a bit easier and cooler. First of all, let's eliminate the issue that the array we're dealing with is an array of Game_Actor objects. What we *want* is an array of agi values, and that's where map comes in.
To put it simply, map is a function you call on an array which takes each element of that array and performs a particular piece of code on it, which you supply to it. It then returns a new array where each element is the result of performing that code. So if our party members have an agi value of 10, 12, 10 and 15 respectively...
Code:
$gameParty.members().map(member => member.agi);
Will return [10, 12, 10, 15].
The "member" after the first bracket is just the name we're giving to the current element of the array. We could have called it almost literally anything. I could have called it "banana" and done "banana.agi" but I like to give my iteration variables meaningful names. 😛
So, great! We now have an array of numbers. So we could do
Code:
let aryAgi = $gameParty.members().map(member => member.agi);
let totalAgi = 0;
for (var i = 0; i < aryAgi.length; i++) {
totalAgi += aryAgi[i];
}
let avgAgi = totalAgi / aryAgi.length;
And that's a huge improvement! We only have one call to $gameParty.members() in the whole thing, so we're eliminating some unnecessary function calls. But it still has the same need for a totalAgi variable and a for loop and it just seems like it should be a bit easier, y'know? And that's where we couple our map with the very powerful reduce.
Reduce is a function which, again, is called on an array. It takes two parameters rather than map's one: one for the current element, and one that holds a value which persists throughout all iterations. Or for our purposes, the total. To wit:
[1, 5, 7, 10].reduce((total, value) => total + value);
Will return 23. You can already see where I'm going with this:
Code:
let aryAgi = $gameParty.members().map(member => member.agi);
let totalAgi = aryAgi.reduce((agi, total) => total + agi);
let avgAgi = totalAgi / aryAgi.length;
And presto, we've reduced (lol) 5-6 lines of code down to 3. But it gets even better, because in JS you can chain function calls:
Code:
let avgAgi = $gameParty.members().map(member => member.agi).reduce((total, agi) => total + agi) / $gameParty.members().length;
So we can do all that in a single line of code! This way does need another call to $gameParty.members() to get the number of elements, but I think you'll agree it's a lot more compact.
These aren't the only ways to use map effectively either. Let's say you have an array of strings and want to convert them to lowercase for comparing with specific words/phrases:
Code:
let strings = ["tHiS", "iS", "A", "stRiNG", "ArRaY"];
let lcStrings = strings.map(string => string.toLowerCase());
lcStrings will return ["this", "is", "a", "string", "array"] and you can now compare the values without caring how they were passed in the first place.
Array has some other cool functions as well, but these two are my favourites and used together they can be incredibly powerful. Hope this was helpful!
Edit: Thanks to @Solar_Flare for also pointing out that this can be done with just reduce:
Code:
let avgAgi = $gameParty.members().reduce((total, member) => total + member.agi, 0) / $gameParty.members().length;