<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Christopher Tiller on Medium]]></title>
        <description><![CDATA[Stories by Christopher Tiller on Medium]]></description>
        <link>https://medium.com/@christiller2015?source=rss-679004efb876------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*66vgHQ-vGwkbm5vo.</url>
            <title>Stories by Christopher Tiller on Medium</title>
            <link>https://medium.com/@christiller2015?source=rss-679004efb876------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 09:30:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christiller2015/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Machine Learning and GA’s]]></title>
            <link>https://medium.com/@christiller2015/machine-learning-and-gas-d8ee52023aa?source=rss-679004efb876------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ee52023aa</guid>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Christopher Tiller]]></dc:creator>
            <pubDate>Tue, 08 May 2018 01:07:45 GMT</pubDate>
            <atom:updated>2018-05-08T01:07:45.930Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately I’ve been on a learning kick, and the thing that has grabbed my interest as of late is Machine Learning. What the heck is it? How does it work? How does a fellow like yourself with no knowledge of it get started? No worries! All will be revealed soon with this article.</p><h3>What is Machine Learning?</h3><p>Long story short, you’re giving a machine the ability to “learn”, where learning is described as “progressively improving at a given task”. You tell the machine to do something, and then you tell it how it can know if it did better at that task. Afterwards, you let it work its magic.</p><p>Let me reiterate, you are not programming the machine to *do* a specific task. You’re programming it to learn how to get better at that task. Therein lies all of the difference.</p><h3>Why do we use it?</h3><p>Well, as any functional human being can tell you, the real world can get really, really complicated really fast. In some cases if we were to program some problems by brute force, we end up with thousands or even hundreds of thousands of calculations. This isn’t practical or feasible for a programmer to do, not to mention the massive amount of time wasted!</p><p>As a second reason, again, the real world is thoroughly complex. This means that in addition to the sheer work hours that would be necessary to create a solution, the best solution may not be obvious to us if we were to directly calculate it. It is, in many ways, far more effective to just have something else “figure it out” for us. That’s where Machine Learning comes in! Specifically, Genetic Algorithms.</p><h3>What is a Genetic Algorithm?</h3><p>A genetic algorithm is a common and central technique used in machine learning. The entire idea is based on the whole “survival of the fittest” business. Basically, you randomly create a bunch of solutions to your problem. You then take the solutions that are more “fit”, breed those solutions together and you now have their children. Mutate their children, and repeat that process until you get something that fits well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwvK_Bn4tztMBIZ5ePNH8Q.jpeg" /><figcaption>That’s how it works!</figcaption></figure><h3>So, how do we do it?</h3><p>Glad you asked, curious reader! As it just so happens I have an example of a simple machine learning program made for you in C#! This is coded from scratch with no frameworks or external functions, so it shouldn’t be too difficult to recreate in a language of your choosing.</p><p>Let’s get started with the individual:</p><h3>Individual.cs:</h3><p>This contains the fitness, the genelength, and the list of genes. It also just so happens to contain the constructors for the individual, and a function to calculate their fitness.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Tasks;</pre><pre>namespace Genetic_Algorithm<br>  {<br>    class Individual<br>    {<br>      public int fitness = 0;<br>      // Free to modify geneLength<br>      static public int geneLength = 20;<br>      public int[] genes = new int[geneLength];</pre><pre>      // Calculates the fitness for this individual.<br>      // If the gene value matches our desired binary, then the fitness increases.<br>      public void FitnessCalc()<br>      {<br>        for(int i = 0; i &lt; geneLength; i++)<br>        {<br>          if(genes[i] == 1)<br>          {<br>            fitness++;<br>          }<br>        }<br>      }<br>      <br>      // The individual constructor.<br>      public Individual()<br>      {<br>        for(int i = 0; i &lt; genes.Length; i++)<br>        {<br>          // Generates a bit that is either 1 or 0.<br>          genes[i] = Services.Rand.Next() % 2;<br>        }<br>      }<br>      <br>      //individual overload, takes an array.<br>      public Individual(int[] genecombination)<br>      {<br>        for(int i = 0; i &lt; geneLength; i++)<br>        {<br>        // Clone to avoid pass by reference issues.<br>          genes = (int[])genecombination.Clone();<br>        }<br>      }<br>    }<br>  }</pre><h3>Population.cs:</h3><p>Contains values for the population size, the fittest and second fittest values, and an array of all of the individuals.</p><p>It contains a method to initialize the population, to get the fittest individuals, and make every individual calculate their own fitness.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Tasks;</pre><pre>namespace Genetic_Algorithm<br>{<br>  class Population<br>  {<br>    // Free to modify popsize.<br>    static public int PopSize = 30;<br>    public int fittest = 0;<br>    public int secondFittest = 0;<br>    public Individual[] individuals = new Individual[PopSize];<br>    <br>    // Initialize population<br>    public void InitializePopulation(int size)<br>    {<br>      for (int i = 0; i &lt; individuals.Count(); i++)<br>      {<br>        individuals[i] = new Individual();<br>      }<br>    }<br>    <br>    // Get the fittest individual(s) Free to modify percentage.<br>    public Individual[][] GetFittestIndividuals(int percentage)<br>    {<br>      // Sort the individuals:<br>      var fitIndividuals = new Individual[2][];<br>      var individualCount = percentage * individuals.Count() / 100;<br>      fitIndividuals[0] = individuals.OrderByDescending(o =&gt; o.fitness).Take(individualCount).ToArray();<br>      fittest = fitIndividuals[0].First().fitness;<br>      secondFittest = fitIndividuals[0].Distinct().Skip(1).First().fitness;</pre><pre>      // The least fit individuals<br>      fitIndividuals[1] = individuals.OrderBy(o =&gt; o.fitness).Take(individualCount).ToArray();<br>      return fitIndividuals;<br>    }<br>    <br>    public void CalculateFitness()<br>    {<br>      // We calculate the fitness of each individual.<br>      for(int i = 0; i &lt; individuals.Count(); i++)<br>      {<br>        individuals[i].FitnessCalc();<br>      }</pre><pre>    // After calculating the fitness, we find the fittest individuals.<br>      GetFittestIndividuals(10);<br>    }<br>  }<br>}</pre><h3>Scheme.cs:</h3><p>Contains a variable for the entire population, for the fittest genes in a population, one to create a child gene, and one to calculate the current generation.</p><p>More importantly, it contains our Selection, Crossover, Mutation, offspring, and new population creation functions. These are what handle the process outlined earlier.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Tasks;</pre><pre>namespace Genetic_Algorithm<br>{<br>  class Scheme<br>  {<br>    public Population population = new Population();<br>    public Individual[] fittest;<br>    int[] childGene = new int[Individual.geneLength];<br>    public int generationCount = 0;</pre><pre>    // Selection<br>    public void Selection()<br>    {<br>    // Getting all of the most fit individuals<br>    fittest = population.GetFittestIndividuals(10)[0];<br>    }</pre><pre>    // Crossover<br>    public int[] Crossover()<br>    {<br>    // Shuffle the array of the fittest first.<br>    var randomizedFittest = fittest.OrderBy(x =&gt; Services.Rand.Next()).ToArray();<br>    // Select a random cutoff fitness<br>    int cutoff = Services.Rand.Next(population.secondFittest);<br>    int count = fittest.Count();<br>    // Get two members of the current generation that are above or equal to this fitness.<br>    Individual[] breedPair = new Individual[2];<br>    for (int i = 0; i &lt; count; i++)<br>    {<br>      // This is the first to breed.<br>      if(fittest[i].fitness &gt;= cutoff)<br>      {<br>        if (breedPair[0] != null)<br>        {<br>          breedPair[1] = randomizedFittest[i];<br>        } else<br>        {<br>          breedPair[0] = randomizedFittest[i];<br>        }<br>      }<br>    }<br>    // Select a random crossover point<br>    int crossOverPoint = Services.Rand.Next(Individual.geneLength);<br>    // Do the crossover.<br>    <br>    for(int i = 0; i &lt; Individual.geneLength; i++)<br>    {<br>      //Console.WriteLine(i);<br>      if(i &lt; crossOverPoint)<br>      {<br>        childGene[i] = breedPair[0].genes[i];<br>      } else<br>      {<br>        childGene[i] = breedPair[1].genes[i];<br>      }<br>    }<br>    return childGene;<br>  }<br>  <br>  // Mutation<br>  public void Mutation()<br>  {<br>    int count = fittest.Count();<br>    // Loop through every child in the new population<br>    foreach (var child in population.individuals)<br>    {<br>      // loop through every gene...<br>      for(int i = 0; i &lt; child.genes.Count(); i++)<br>      {<br>        // Check random probability...<br>        // 1/10 of the time, we mutate.<br>        // Free to modify % 10 &lt;= 1 to change mutation.<br>        if(Services.Rand.Next() % 10 &lt;= 1)<br>        {<br>          //Flip values at the mutation point<br>          if (child.genes[i] == 0)<br>          {<br>            child.genes[i] = 1;<br>          }<br>          else<br>          {<br>            child.genes[i] = 0;<br>          }<br>        }<br>      }<br>    }<br>  }<br>  <br>  // Get fittest offspring<br>  public Individual GetFittestOffspring()<br>  {<br>    if (fittest[0].fitness &gt; fittest[1].fitness)<br>    {<br>      return fittest[0];<br>    }<br>  return fittest[1];<br>  }</pre><pre>  // Create new population<br>  public void CreateNewPopulation()<br>  {<br>    var newPop = new Population();<br>    for(int i = 0; i &lt; Population.PopSize; i++)<br>    {<br>      Crossover();<br>    <br>      var newIndividual = new Individual(childGene);<br>      newPop.individuals[i] = newIndividual;<br>    }</pre><pre>    // Replace the old population with a new population.<br>    population = newPop;<br>    }<br>  }<br>}</pre><h3>Program.cs:</h3><p>This is where we run our program. It handles the initialization, selection, crossing, mutation, and new generations.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Tasks;</pre><pre>namespace Genetic_Algorithm<br>{<br>  class Program<br>  {<br>    static void Main(string[] args)<br>    {<br>      Scheme demo = new Scheme();<br>      // Initialize population<br>      demo.population.InitializePopulation(Population.PopSize);<br>      demo.population.CalculateFitness();</pre><pre>      Console.WriteLine($&quot;Generation: {demo.generationCount} , Fittest: {string.Join(&quot;,&quot;, demo.population.individuals.OrderByDescending(x =&gt; x.fitness).First().genes)} : {demo.population.fittest}&quot;);<br>      <br>      while(demo.population.fittest &lt; Individual.geneLength &amp;&amp; demo.generationCount &lt; 100)<br>      {<br>        demo.generationCount++;<br>        <br>        // Do selection.<br>        demo.Selection();<br>        <br>        // Breed and create a new population.<br>        demo.CreateNewPopulation();<br>  <br>        // Mutate new population.<br>        demo.Mutation();<br>        <br>        // Calculate fitness and log to console.<br>        demo.population.CalculateFitness();<br>  <br>        Console.WriteLine($&quot;Generation: {demo.generationCount} , Fittest: {string.Join(&quot;,&quot;,demo.population.individuals.OrderByDescending(x =&gt; x.fitness).First().genes)} : {demo.population.fittest}&quot;);<br>        }<br>      Console.ReadLine();<br>    }<br>  }<br>}</pre><p>There’s also a Services.cs file that contains the random function:</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Tasks;</pre><pre>namespace Genetic_Algorithm<br>{<br>  class Services<br>  {<br>    static public Random Rand { get; set; } = new Random();<br>  }<br>}</pre><p>And with that, we’re done! Running the program, we get something like:</p><pre>Generation: 0 , Fittest: 1,0,0,1,1,1,1,1,1,0,0,1,1,0,1,1,1,1,0,1 : 14<br>Generation: 1 , Fittest: 1,1,0,1,0,1,1,1,1,0,1,1,0,1,0,1,1,1,1,1 : 15<br>Generation: 2 , Fittest: 1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1 : 16<br>Generation: 3 , Fittest: 1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1 : 17<br>Generation: 4 , Fittest: 1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1 : 18<br>Generation: 5 , Fittest: 1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1 : 18<br>Generation: 6 , Fittest: 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 : 20</pre><p>And that’s all! Some takeaways:</p><p>1: Genetic Algorithms are a totally different way of thinking. Instead of Explicitly programming something, you program something to get better at a task. By doing this it can get scarily close to mimicking real life!</p><p>2: While this example may have completed for some, it may not complete for everyone. That’s perfectly fine, because what we’re looking for is good enough, not perfect. In the real world a lot of solutions are never mathematically exact, and machine learning is no different. As long as you’re really close to the answer you want, then that’s good enough!</p><p>That’s it for this blog post. Let me know what you think in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ee52023aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the heck does Include do!?!?]]></title>
            <link>https://medium.com/@christiller2015/what-the-heck-does-include-do-4ffb283f9af4?source=rss-679004efb876------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ffb283f9af4</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[include]]></category>
            <dc:creator><![CDATA[Christopher Tiller]]></dc:creator>
            <pubDate>Wed, 25 Apr 2018 17:32:51 GMT</pubDate>
            <atom:updated>2018-04-25T17:32:51.109Z</atom:updated>
            <content:encoded><![CDATA[<p>So we’re currently on week… 8? Of our SDG-Proforma cohort, and the last week or so we’ve been working with databases. At the same time, I’ve been tearing my hair out trying to understand one thing:</p><p>Linq includes.</p><p>As my coworkers and instructors can attest, include for some reason had me absolutely stumped. So many things were happening and it seemed that there were so many gotchas that it made no sense whatsoever, but finally, FINALLY I think I have a decent grasp on it.</p><p>So, for the rest of this post I’ll be going over what I’ve learned. Sound good? Great. We’re doing this!</p><p>Since we’re good little developers, we’ll start at the documentation like all good developers do. A quick search gives us:</p><p>ObjectQuery&lt;T&gt;.Include Method</p><p>Specifies the related objects to include in the query results.</p><p>Okay, what does this mean?</p><p>Let’s say for instance I had a SQL database of people. In this database we’ll say that we have three tables. These tables are going to be called People, Banks, and Addresses. People and Banks have a many-many relation, and Addresses have a many-many relation with people.</p><p>Normally, if I were to do a query on people, but wanted data from any of the other tables, I would have to do a where, or a first, or any sort of method that returns an implicit join. With Include, however, I can explicitly say that “hey, I want to include Banks and Addresses in the query results”, like so:</p><pre>Var query = context.People.Include(i =&gt; i.Addresses).include(I =&gt; i.Banks);</pre><p>And then query would have a reference to both addresses and banks inside of the query. I could then do operations that involve both.</p><p>Essentially, it is the same as doing a SQL JOIN statement on the ID of each. In SQL, it would look something like:</p><pre>SELECT *<br>FROM People<br>JOIN People ON PeopleAddresses.ID = People.ID<br>JOIN PeopleAddresses ON Addresses.ID = PeopleAddresses.ID<br>JOIN People ON PeopleBanks.ID = People.ID<br>JOIN PeopleBanks ON Banks.ID = PeopleBanks.ID</pre><p>Or something roughly to that effect.</p><p>As you can see, it saves us quite a bit of work, and since we’re explicitly saying what we’re querying, we get a bit of a performance boost.</p><p>As a final bit of information, a slight gotcha. Since we’re doing many-many relationships if we tried to do something like: query.people.addresses we’d have some issues, mostly because it’s pulling the entire list instead of just a single item, so in order to work with the data you need to make sure you run a foreach, first, or select statement to get a single item.</p><p>And that’s it! Hope you enjoyed, and hope it was helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ffb283f9af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Randomization]]></title>
            <link>https://medium.com/@christiller2015/working-with-randomization-46b6d7c2c4d9?source=rss-679004efb876------2</link>
            <guid isPermaLink="false">https://medium.com/p/46b6d7c2c4d9</guid>
            <category><![CDATA[random]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Christopher Tiller]]></dc:creator>
            <pubDate>Tue, 03 Apr 2018 19:35:09 GMT</pubDate>
            <atom:updated>2018-04-03T19:35:09.538Z</atom:updated>
            <content:encoded><![CDATA[<p>So lately we’ve been working on a project to create a game of Jeopardy. I could talk for days about all of the problems I encountered, all of the fun tips and tricks I picked up along the way, as well as my fun times with Angular.</p><p>But I won’t do that.</p><p>Instead I’ll talk about a very particular problem that actually interested me quite a bit, which was this:</p><blockquote>“Create 3 random daily doubles”</blockquote><p>For simplicity’s sake, let’s assume that we’re already further ahead in the project and our board looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*rGsdcq0V18_A0ny9Zxgy8A.png" /><figcaption>Seems like your typical jeopardy board, right?</figcaption></figure><p>Also for simplicity’s sake, let’s assume that our data currently exists in a JavaScript array with five categories, each containing an array with five clues, of which are objects. (I know the picture has four, but whatever!)</p><p>With that out of the way, let’s break this down a bit!</p><h3>Breaking it down</h3><p>The problem, again, is to “create 3 random daily doubles”. From this we know two things:</p><p>1: We need to get our daily doubles randomly, as in they cannot be reliably predicted.</p><p>2: We need to get exactly 3 of them. No more, no less.</p><p>That’s it! So now we need to get started.</p><p>Because we’re working with objects, and objects are <strong>pass by reference</strong>, we don’t need to worry too much. We’ll settle for adding a “dailyDouble” property to them. This will be a Boolean. If it is a daily double it will have this property set to true.</p><p>So, onto the interesting bit, the randomization!</p><p>This shouldn’t be bad, right? Let’s start by just throwing every single object item into an array, like so:</p><pre>let allClues = [];<br>for( let i = 0; i &lt; data.length; i++) {<br>  for(let j = 0; j &lt; data[i].length; j++) {<br>    allClues.push(data[i][j];<br>  }<br>}</pre><p>This will place every object into the array, making it easier for us to manipulate. For the randomization, this will take a bit of thinking. We *could* just create three random variables, and then grab those items:</p><pre>allClues[Math.Floor(Math.random() * allClues.length)].dailyDouble = true;</pre><p>and then do that a total of three times:</p><pre>for(let I = 0; i &lt; 3; i++) {<br>   allClues[Math.Floor(Math.random() * allClues.length)].dailyDouble = true;<br>}</pre><p>But then we run into an issue. How do we avoid duplicates?</p><p>Well, we could fix that by placing it in an array, and then checking if a value has shown up yet…</p><pre>let temp = [];<br>for(let i = 0; i &lt; 3; i++) {<br>  let randVal = Math.Floor(Math.random() * allClues.length);<br>  if(temp.indexOf(randVal) !== -1) {<br>    allClues[randVal].dailyDouble = true;<br>  }<br>}</pre><p>And this would work! We no longer get duplicates, but we can still get less than three daily doubles. We *must* get three!</p><p>So, let us address this:</p><pre>let temp = [];<br>while(temp.length &lt; 3) {<br>  let randVal = Math.Floor(Math.random() * allClues.length);<br>  if(temp.indexOf(randVal) !== -1) {<br>    allClues[randVal].dailyDouble = true;<br>}</pre><p>And this will work! That is, unless, we get really unlucky and keep getting the same value over and over again. While rare, there is a nonzero probability it can happen, and we want to avoid that.</p><p>So, what do we do then?</p><p>Well, the problem is we want three random items, so why not just randomize the entire array instead? The array in particular isn’t sacred or important beyond being a place to actually hold our data, so we can do with it what we please.</p><p>To do this we can use what is called the durstenfield shuffle. It loops backwards and randomizes the elements.</p><pre>function shuffleArray(array) {<br>  for (var i = array.length — 1; i &gt; 0; i — ) {<br>    var j = Math.floor(Math.random() * (i + 1));<br>    var temp = array[i];<br>    array[i] = array[j];<br>    array[j] = temp;<br>  }<br>}</pre><pre><em>// Taken from </em><a href="https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array?utm_medium=organic&amp;utm_source=google_rich_qa&amp;utm_campaign=google_rich_qa"><em>stackOverflow </em></a></pre><p>So how does this work?</p><p>Use a shuffle algorithm to randomize the array, and then just take the first three values of that list and set the dailydouble value on each of them to true.</p><pre>let dailyDoubles = [];<br>let temp;<br>for(let I = 0; I &lt; allClues.length — 1; i — ) {<br>  let j = Math.floor(Math.random() * (i + 1));<br>  let temp = allClues[i];<br>  allClues[i] = allClues[j];<br>  allClues[j] = temp;<br>}</pre><p>And then:</p><pre>for(let I = 0; I &lt; 3; i++) {<br>  allClues[i].dailyDouble = true;<br>}</pre><p>And voila! We’re done! We have 3 daily double properties on three random clues.</p><p>To recap, the idea was:</p><p>Instead of trying to create random values and use those, instead just randomize your list of values, and pick x amount from that list.</p><p>That’s it! Let me know what you think in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46b6d7c2c4d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filter? Map!? Reduce!?!?]]></title>
            <link>https://medium.com/@christiller2015/filter-map-reduce-a2acd463f9ea?source=rss-679004efb876------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2acd463f9ea</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Christopher Tiller]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 18:25:52 GMT</pubDate>
            <atom:updated>2018-03-19T18:25:52.897Z</atom:updated>
            <content:encoded><![CDATA[<p>So lately I’ve been studying code with SuncoastJS. And as of last weekend, I had a chance to get really, <em>really</em> familiar with JavaScript array methods, and most notably <strong>Filter</strong>, <strong>Map</strong>, and <strong>Reduce</strong>.</p><p>Long story short, they’re awesome!</p><p>The only downside is that at first they’re way difficult to understand, so via this blog post my goal is to break these methods down as clearly as possible. To make it less painful, we’re going to start with Map. Before that, however, let’s make some things clear:</p><p>1: All of these only operate on arrays. The methods only exist on JavaScript arrays.</p><p>2: All of these methods operate on the values of an array and return a new array. They DO NOT mutate the input array.</p><p>3: Every single one of these is shorthand for something you can already do in JavaScript.</p><p>With that out of the way, let’s get started!</p><h3><strong>Array.prototype.map()</strong></h3><p>What it must take in: An array</p><p>What it gives back: A new array with every value changed somehow.</p><p>Array.map() is great because it gives you a shorthand way to change each value of an array. When called, you have the option to provide a function where the first parameter is the value of the array that you’re operating on, along with optional parameters to get the index of that element, and one to get the entire array. After the function you have an option to decide the value of this, but we don’t need to worry about that right now.</p><p>Inside of the array map, you have an option to provide a function, and that function’s return value determines what you get back. So if I had the code snippet:</p><pre>let arr = [1,2,3,4,5];</pre><pre>let newArr = arr.map((num) =&gt; {<br>  return num * 2;<br>});</pre><pre>console.log(newArr);</pre><p>I would expect to get:</p><pre>[2,4,6,8,10]</pre><p>See? Array.map() ran a function on every single value of the array, and then spat that back out into a new array for me.</p><p>That code snippet would essentially be equivalent to:</p><pre>let arr = [1,2,3,4,5];<br>let newArr = [];</pre><pre>for(let I = 0; I &lt; arr.length; i++) {<br>  let newVal = arr[i] * 2;<br>  newArr.push(newVal);<br>}</pre><pre>console.log(newArr);</pre><p>As you see, we still get the same result: [2,4,6,8,10]</p><h3><strong>Array.prototype.filter()</strong></h3><p>What it must take in: An Array</p><p>What it gives back: A new array with all values that pass a given test.</p><p>Array.filter() gives you a nice shorthand to pull out information from an array. Similar to map, you need to call a function with a given element. Of course, the index and array parameters are still available as well. You can think of filter as nearly identical in terms of syntax, just it gives you back something else.</p><p>For example:</p><pre>const arr = [1,2,3,4,5];</pre><pre>const newArr = arr.filter((elem) =&gt; {<br>  return num &lt; 3;<br>});</pre><pre>console.log(newArr);</pre><p>I would expect to get: [1,2]</p><p>Array.filter() looked at the values that were coming in, and then only returned them if they passed the specified test!</p><p>It is equivalent to the following longhand:</p><pre>const arr = [1,2,3,4,5];<br>let newArr = [];</pre><pre>for(let I = 0; I &lt; arr.length; i++) {<br>  if(arr[i] &lt; 3) {<br>    newArr.push(arr[i]);<br>  }<br>}</pre><pre>console.log(newArr);</pre><p>and as before, we get: [1,2]</p><h3><strong>Array.prototype.reduce()</strong></h3><p>Strap in folks, this is a fun one!</p><p>So while Array.map() had the goal of changing every single value of an array, and Array.filter() had the goal of only getting values of an array that pass a certain test, reduce has the goal of combining everything down into a single value, or “reducing” an entire array to a single value.</p><p>Similar to the prior two methods, it does operate on an array, and it does take in a function parameter. The difference begins with the internal function. Inside of that function, we take two values, normally called “accumulator” and “value”, respectively. To break it down, “accumulator” is the combination of every single element so far, while value is just the current element. As reduce runs, it takes the return from the function and makes that the new accumulator for every single element.</p><p>Eyes starting to cross? Don’t worry, here’s an example!</p><pre>const arr = [1,2,3,4,5];</pre><pre>let combinedVal = arr.reduce((acc, val) =&gt; {<br>  return acc + val;<br>});</pre><pre>console.log(combinedVal);</pre><p>and we’ll get: 15</p><p>So what the heck just happened there? Let’s break it down step-by-step.</p><p>For the first run of arr.reduce, we essentially had:</p><pre>return 1 + 2;</pre><p>1 + 2 = 3, so that becomes our new accumulator for the next run.</p><p>On the second run of arr.reduce, we have:</p><pre>return 3 + 3;</pre><p>3 + 3 = 6, so that becomes our new accumulator for the next run:</p><pre>return 6 + 4;</pre><p>Alright, that’s fine, that gives us 10! And on the final run we have:</p><pre>return 10 + 5;</pre><p>See what happened? It took the value, returned it, and made that value the new accumulator on each run, effectively “summing” all of the elements together.</p><p>For those of you still curious, that would be equivalent to:</p><pre>let arr = [1,2,3,4,5];<br>let sum = 0;<br>for(let I = 0; I &lt; arr.length; i++) {<br>sum += arr[i];<br>}<br>console.log(sum);</pre><p>And that’s it!</p><p>So, to recap:</p><p>-<strong>Map</strong> is for when you want to change every value of the array somehow.</p><p>-<strong>Filter</strong> is for when you want to get a few values that pass a test out of an array.</p><p>-<strong>Reduce</strong> is for when you want to somehow combine all values of the array.</p><p>-All three methods create a <strong>brand new array</strong>.</p><p>-All three methods take in a function.</p><p>And that’s it! Hope it was helpful. Let me know if you have any questions in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2acd463f9ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>