CodeNewbie Community 🌱

Cover image for Commit16 //#JavaScript30 - Day 4 [Array Cardio Day 1]
Janet Webster
Janet Webster

Posted on • Updated on

Commit16 //#JavaScript30 - Day 4 [Array Cardio Day 1]

Photo of my work in Visual Studio Code


I am learning with Skillcrush. Please check them out and consider signing up if you're looking to break into tech! Receive $250 off your course by using the link above. Use the coupon code: TWIXMIXY
NOTE: this discount is for Break Into Tech + Get Hired package exclusively. It's the same program I am participating in!


Today's challenge comes from JavaScript30.

Yesterday was super busy! I met with my bootcamp TA and worked on my JS React course. I wasn't able to work on this prior to my chiropractic appointment in the afternoon.

I also was coaching with Foundation For Girls yesterday afternoon. I did attempt to jump back into it last night, but I could tell my brain wasn't functioning, so I decided to call it and get back to it today.

JavaScript30 - Day 4

First we have some data objects already laid out for us.

    // 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 }
    ];
Enter fullscreen mode Exit fullscreen mode

And we also have a people array, which has strings of their names.

    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'
    ];
Enter fullscreen mode Exit fullscreen mode

1. Filter the list of inventors for those who were born in the 1500s.
Array.prototype.filter()

const fifteen = inventors.filter(inventor => (inventor.year >= 1500 && inventor.year <= 1599))
Enter fullscreen mode Exit fullscreen mode

This is a new way of writing a filter from what I've seen before. Before it looked more like... a function? This way has the return already built in. I guess. Not sure I fully understood the previous way of writing it, but this way is more succinct from what the instructor is referencing.

console.table(fifteen);
Enter fullscreen mode Exit fullscreen mode

Now this is a console log, but it's with .table! Which is really cool. I love how it displays the information in the console.

Console table

2. Give us an array of the inventors first and last name
Array.prototype.map()

const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`);
console.log(fullNames);
Enter fullscreen mode Exit fullscreen mode

Here we are concatenating the first name and last name together for the inventors' objects. Then running the console to make sure the data comes through, which it does!

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

To begin he wrote up the function as such:

    const ordered = inventors.sort(function(a, b) {
      if(a.year > b.year) {
        return 1;
      } else {
        return -1;
      }
    });
    console.table(ordered);
Enter fullscreen mode Exit fullscreen mode

But then just like the first prompt on this lesson, he shortened it to be the following:

const ordered = inventors.sort((a, b) => a.year > b.year ? 1 : -1);
    console.table(ordered);
Enter fullscreen mode Exit fullscreen mode

From what I understand the a and b are placeholders that can be labeled whatever you want, but they are to make the contrast between the inventors to begin sorting them by their birthdate year.

Console table of inventors by DOB

4. How many years did all the inventors live?
Array.prototype.reduce

I'm guessing we are going to be doing some math now!

.reduce - allows you to build something in a much cleaner way
Otherwise you have to declare the variable and then right a for...of loop or the function, etc.

const totalYears = inventors.reduce((total, inventor) => {
 return total + (inventor.passed - inventor.year);
    }, 0);

console.log(totalYears);
Enter fullscreen mode Exit fullscreen mode

So we had to add the "0" to give a starting point for the total, if I'm understanding this correctly.

Otherwise this was a pretty typical function with a return to have the years passed minus the years born aka year.

totalYears combined all the living years of all of the inventors together. Which came out to 861 for me.

5. Sort the inventors by years lived

    const oldest = inventors.sort(function(a, b) {
      const lastGuy = a.passed - a.year;
      const nextGuy = b.passed - b.year;
      if (lastGuy > nextGuy) {
        return -1;
      } else {
        return 1;
      }
    })

    console.table(oldest);
Enter fullscreen mode Exit fullscreen mode

Again, he wrote out the function in long form again.

Instead of having the conditional IF statement, he rewrote it as a return.

return lastGuy > nextGuy ? -1 : 1;
Enter fullscreen mode Exit fullscreen mode

Same result!

Console table sorting years lived

6. Create a list of Boulevards in Paris that contain 'de' anywhere in the name

const category = document.querySelector('.mw-category');
const links = Array.from(category.querySelectorAll('a'));

const de = links
                .map(link => link.textContent)
                .filter(streetName => streetName.includes('de'));
Enter fullscreen mode Exit fullscreen mode

I'm not fully sure how this is going to work because the instructor hasn't connected this yet to the wikipedia URL of all the streets.

However, these are variables being declared to find the specific data points within the website.

Something new was having both .map and .filter listed in the same declaration. Just have to leave out the semi-colon after map.

Looks like he commented this out in the next step for now, until we do some other work...

7. Sort exercise

    // Sort the people alphabetically by last name
    const alpha = people.sort((lastOne, nextOne) => {
      const [aLast, aFirst] = lastOne.split(', ');
      const [bLast, bFirst] = nextOne.split(', ');
      return aLast > bLast ? 1 : -1;
    });
    console.log(alpha);
Enter fullscreen mode Exit fullscreen mode

OK. This was a lot. I'm definitely a bit muddled on it. Basically, we are grabbing the people from the string array at the top. We are differentiating them from each other so they can be sorted by doing lastOne and nextOne. We are using an arrow function instead of actually typing out "function".

Then we are declaring variables to define the last and first names, using .split to admit the comma and space between last name and first name.

Finally we are returning the data to say the A last name is greater than the B last name. The part I still don't really get is the ? 1 : -1. If you can explain it to me, please comment on the post! I know when he switched it to be ? -1 : 1 then it sorted them in the opposite direction.

8. Reduce exercise

We are immediately given a new array variable called data.

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
Enter fullscreen mode Exit fullscreen mode

He wants us to sum up the instances of each of these.

    const transportation = data.reduce(function(obj, item) {
      if(!obj[item]) {
        obj[item] = 0;
      }
      obj[item]++;
      return obj;
    }, {
      // car: 0,
      // walk: 0,
      // truck: 0,
      // bike: 0,
      // van: 0
    });

    console.log(transportation);
Enter fullscreen mode Exit fullscreen mode

Console log list of how many of each transportation

OK! So yes, this one is a bit complex. I left in the commented out vehicle breakdown of each because we ended up leaving that object space blank. Honestly I'm not sure why we would fill it out to begin with. Maybe that's an old style of coding and he's showing there are new ways to get this info.

First off we're saying IF the object item does not exist, then it would be set to zero. Otherwise if the object item exist add one count of it. Then return the object output. At least that's my take away from going through the lesson and reading the code. I would LOVE to have your insight on this... cuz I'm still in the heavy learning phase.

If you are a pro at Arrays or feel like you're a bit ahead of me at this point, please comment below and drop some knowledge on me!

GitHub Repo of Array Cardio Day 1

Top comments (0)