<h1>map,reduce,filter</h1>
Making a combat sequence.<br/>
Alright today I'll be demonstrating the usages of map,reduce and filter in the context of a battle sequence.
<h2>
Ready
</h2>
Here's the setup, we have a battlefield with 6 units, consisting of both friendlies and hostiles.
<pre>
const field = [
{ _id: 0, type: 'self' },
{ _id: 1, type: 'ally' },
{ _id: 2, type: 'ally' },
{ _id: 3, type: 'hostile' },
{ _id: 4, type: 'hostile' },
{ _id: 5, type: 'hostile' }
];
</pre>
We'll elaborate more on our schema as we progress the development of our game. For now, our game engine is non-existant. The only built-in function is the `attack` function.
<pre>
const attack = target => target.health--;
</pre>
Yes. Our units now have a health property. Let's assign each with a default of `3` health points. This where I get to introduce our handy `map` function. I want to assume that you, the reader, already knows how to accomplish this using a `for` loop so I can omit that and get straight to showing how it can be done with map function.
<pre>
const fieldv2 = field.map(units => Object.assign(unit, { health:3 }));
</pre>
Right, we now have a version 2 of our battlefield. Previously all units health value would have been `undefined` which could mean they were either dead or alive, depending on how you want to look at it, but we've changed that and made them all mortal by giving them 3 health points each.
That's the `map` function in action. To put in my own terms, what `map` does is it creates a new array by traversing a given array, takes each value and runs it through the given transformation function.
<p>
Here's another example where, let's say, we crank up the difficulty up by a notch becasuse we're hardcore, and give all hostiles additional health points.
</p>
<pre>
const fieldv2_hard = fieldv2.map(unit => {
if (unit.type === 'hostile') unit.health++;
return unit;
});
</pre>
<p>
Don't forget the last return statement,...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.