How to use Array.Reduce() for JavaScript and the importance of DELETE EVERYTHING AND START FROM BEGINNING!

This short(sike) blurb is to highlight something I am very proud of myself of not only figuring it out, but realizing sometimes you just have to toss away what you had before! So I was watching this video tackling array practices because I always shy away from them and always felt there were daunting. I never understood the usage of => or mapping or reduce, so why not work on that! My biggest challenge was overall: Figuring out reduce.

So from what I gather from the MDN Article it is of the following:

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

Honestly? I do not know what in the WORLD I just read. BUT! And bear with this noobie speaking, I am believing it takes in values, does arithmetic I say I want it to,

And then returns one value which is the summation of values I passed through. Did I hit a hole in one yet? Swing!

Okay! So my first draft of my code initially looked like this after reading documents(and stalking stack overflow :-) )

function sum(inventors){
 const reducer = (sum, val) => inventors.year + inventors.passed;
 const initialValue = 0;
 return inventors.reduce(reducer, initialValue);
}

let result = sum(inventors);
console.log(result);

I kept getting a NaN and it was frustrating. Initially, I was expecting to have rows of each individual total years lived, but that was because I misunderstood and missed the key part of reduce saying that The final result of running the reducer across all elements of the array is a single value. Woops!

So, I asked some good people I know for small pair programming to get a fresh perspective of what I was doing. And you know what was best for me to get over my confusion?

I deleted everything and started from the top, this time with clarification from friends. Rewriting definitely helped me get a clearer picture and funny enough, I got the right answer thanks to friends pointing out when I was still thinking I was doing something wrong LOL!!!!!!!! This time, this is how my code looked:

//Array.prototype.reduce()
//My Notes
//Goal is to get the sum of years people live, inventors.passed - inventors.year
//We are using reduce method to accomplish this.

//array we have is inventors earlier up in code
//Now we have function to combine the values together
//let call the function "Sum" with parameters val(before I did inventors, which was incorrect)

function sum(val){
 //initializing the initial value:
 const initialValue = 0;

 //variable called reducer that does the arithmetic of pass-year
 //Want it to get each individual inventors' length of how long 
 //They lived, and add them all up together
 const reducer = (sum, val) => val.passed - val.year + sum;

 //return the result
 return val.reduce(reducer, initialValue)
}

 //now to pass the inventor array through the sum function
 sumResult = sum(inventors);
 console.log(sumResult);

As a result, the console.log showed me the answer was 861. I was honestly proud of myself to do this without seeing solution first and its my first time doing a reduce . It really makes a difference to properly document and comment out my journey, and sometimes start from the beginning :-) The life of a self-learning Developer!

Here is the full code version for people to see for themselves:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Array Cardio 💪</title>
</head>

<body>
  <p><em>Psst: have a look at the JavaScript Console</em> 💁</p>
  <script>
    // Get your shorts on - this is an array workout!
    // ## Array Cardio Day 1

    // Some data we can work with

    const inventors = [{
        first: 'Albert',
        last: 'Einstein',
        year: 1879,
        passed: 1955
      },
      {
        first: 'Isaac',
        last: 'Newton',
        year: 1643,
        passed: 1727
      },
      {
        first: 'Galileo',
        last: 'Galilei',
        year: 1564,
        passed: 1642
      },
      {
        first: 'Marie',
        last: 'Curie',
        year: 1867,
        passed: 1934
      },
      {
        first: 'Johannes',
        last: 'Kepler',
        year: 1571,
        passed: 1630
      },
      {
        first: 'Nicolaus',
        last: 'Copernicus',
        year: 1473,
        passed: 1543
      },
      {
        first: 'Max',
        last: 'Planck',
        year: 1858,
        passed: 1947
      },
      {
        first: 'Katherine',
        last: 'Blodgett',
        year: 1898,
        passed: 1979
      },
      {
        first: 'Ada',
        last: 'Lovelace',
        year: 1815,
        passed: 1852
      },
      {
        first: 'Sarah E.',
        last: 'Goode',
        year: 1855,
        passed: 1905
      },
      {
        first: 'Lise',
        last: 'Meitner',
        year: 1878,
        passed: 1968
      },
      {
        first: 'Hanna',
        last: 'Hammarström',
        year: 1829,
        passed: 1909
      }
    ];

    const people = [
      'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd', 'Beckett, Samuel', 'Blake, William',
      'Berger, Ric', 'Beddoes, Mick', 'Beethoven, Ludwig',
      'Belloc, Hilaire', 'Begin, Menachem', 'Bellow, Saul', 'Benchley, Robert', 'Blair, Robert', 'Benenson, Peter',
      'Benjamin, Walter', 'Berlin, Irving',
      'Benn, Tony', 'Benson, Leana', 'Bent, Silas', 'Berle, Milton', 'Berry, Halle', 'Biko, Steve', 'Beck, Glenn',
      'Bergman, Ingmar', 'Black, Elk', 'Berio, Luciano',
      'Berne, Eric', 'Berra, Yogi', 'Berry, Wendell', 'Bevan, Aneurin', 'Ben-Gurion, David', 'Bevel, Ken',
      'Biden, Joseph', 'Bennington, Chester', 'Bierce, Ambrose',
      'Billings, Josh', 'Birrell, Augustine', 'Blair, Tony', 'Beecher, Henry', 'Biondo, Frank'
    ];

    // Array.prototype.filter()
    // 1. Filter the list of inventors for those who were born in the 1500's
    // const fifteenHundred = inventors.filter(inventor => (inventor.year >= 1500 && inventor.year <= 1600))

    // console.table(fifteenHundred)

    //another way of writing

    // const fifteenHundrend2 = inventors.filter(function(inventor){
    //   if(inventor.year >= 1500 && inventor.year <= 1600){
    //     return true;
    //   }

    // });



    // Array.prototype.map()
    // 2. Give us an array of the inventors first and last names
    // const fullNames = inventors.map(inventor => inventor.first + " " + inventor.last);

    // console.log(fullNames);


    // Array.prototype.sort()
    // 3. Sort the inventors by birthdate, oldest to youngest

    // //my solution
    // function compareYears(a, b) {
    //    return a.year - b.year;
    //  }
    // //Sort the birth years by descending order
    // let sortedYears = inventors.sort(compareYears);
    // console.table(sortedYears);

    // //video's solution
    // // let orderedYears = inventors.sort(function (a, b) {
    // //   if (a.year > b.year) {
    // //     return 1;
    // //   } else {
    // //     return -1;
    // //   }
    // // })

    // let ordered = inventors.sort((a,b) => a.year > b.year ? 1 : -1);

    // console.table(ordered);


    // Array.prototype.reduce()
    // 4. How many years did all the inventors live all together?

    //My Notes
    //Goal is to get the sums of years people live, inventors.passed - inventors.year
    //We are using reduce method to accomplish this.

    //array we have is inventors earlier up
    //Now we have function to  combine the values together
    //lets call the function "Sum" with parameters val

    function sum(val) {

      //initializing the initial value:
      const initialValue = 0;

      //variable called reducer that does the arithmetic of pass-year
      //Want it to get each individual inventors' length of how long they lived
      const reducer = (sum, val) => val.passed - val.year + sum;

      //return the result
      return val.reduce(reducer, initialValue)
    }

    //now to pass the inventor array through the sum function we did
    sumResult = sum(inventors);
    console.log(sumResult)

    // 5. Sort the inventors by years lived

    // 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
    // https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris


    // 7. sort Exercise
    // Sort the people alphabetically by last name

    // 8. Reduce Exercise
    // Sum up the instances of each of these
    const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car',
      'truck'
    ];
  </script>
</body>

</html>

It's pretty neat documenting the bumps and roads along the way. Its astonishing how much one can grow in due time!

Here's a silly way I try to make Array.reduce make sense to me:

We are taking kitchen items for ONE box labeled "kitchen"

We moving out! So! The kitchen items can represent the array of values(say [1,2,3]) w.e. The box with label is the summation of all the kitchen items (in the array). Us putting the items in box is the "reducer function" where all these several, spread out messy kitchen items are neatly put in a box that when we are done, we got just ONE box aka the sum of the values.

Sorry if it sounds silly, but I try to make it make sense for me!

Mind you the putting into box can be anything! Take two kitchen items to put in box(adding), break a kitchen item before putting in box(subtract) for simple examples. Cant explain how multiply or divide will work in rea life but LMAO hope the gist is understood. I'll figure it out!

Update: I was told the following by a friend: Not just math/arithmetic though. You can use it to take an array of objects and turn it into a single object for example. Or you could use it to turn an array of strings into a single string."

So that's like baking a delicious Apple pie! Several ingredients coming together to make one yummy tasty treat!! Hope the delicious analogy helps! Are you making a pie? A stew? A brownie? Depends on what you want to make (the function passed to reduce).

That function is the recipe. Reduce just follows the recipe with the ingredients you give it. So if you pass it a recipe for brownies but give it ingredients for a stew, you get garbage. But if you pass it brownie ingredients and a brownie recipe you get brownies!