DEV Community

loading...
Cover image for JavaScript-30-Day-4

JavaScript-30-Day-4

KUMAR HARSH
The best way to learn is to teach. Programmer by Passion and Developer for Fun, and I love sharing my journey with everyone.
Updated on ・6 min read

ss

click for demo

Day 4 of JavaScript-30 focusses mainly on core JavaScript fundamentals, we do a bunch of short exercises each targeting one or more than one array methods. I'll summarize each one real quick.

Lessons Learned

  • first thing I learned is we can use console.table instead of console.log to display it pretty and it was so much better than console.log as you can see on the screenshot I provided

Now I'll give a quick example of the objects we would work with today so that you can understand better when which key is used and what it contains.

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

Filtering Things!

  • First method was Array.prototype.filter() Question: Filter the list of inventors for those who were born in the 1500's

According to MDN:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The way filter works is we pass it a function and that function is going to loop over every single item in our array and for each item we can decide if we want to keep that item or not. By returning a true we mean that we want to keep that item also there is no need to return a false here. I'll give the solution in both old syntax and latest ES6 arrow function way.

const fifteen = inventors.filter(function (inventor) {
         if (inventor.year >= 1500 && inventor.year < 1600) {
           return true; // keep it!
         }
       });
      console.table(fifteen);
Enter fullscreen mode Exit fullscreen mode
const fifteen = inventors.filter(
        (inventor) => inventor.year >= 1500 && inventor.year < 1600
      );
console.table(fifteen);
Enter fullscreen mode Exit fullscreen mode

Mapping Things

  • now we'll be using Array.prototype.map(). Question: Give us an array of the inventors first and last names

According MDN:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Map takes in an array, it does something with that array and then returns a new array but of the same length.

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

Sorting Things

  • next we work with Array.prototype.sort(). Question: Sort the inventors by birthdate, oldest to youngest

According to the MDN:

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values

The way sort works is suppose you get 2 items and you have them in your hand and you are asked to sort just these 2 items and return 1 if T and -1 if false (and just like items keep bubbling up and down in the array)

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

we can shorten this code by using arrow functions and ternary operator

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

Reducing Things

  • next one is Array.prototype.reduce() Question: How many years did all the inventors live all together?

Now this one is a bit tricky so instead here is a great article to read about reduce method.

const totalYears = inventors.reduce((total, inventor) => {
        return total + (inventor.passed - inventor.year);
      }, 0);
      console.log(totalYears);
Enter fullscreen mode Exit fullscreen mode
  • we had another sorting challenge Question: 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;
        return lastGuy > nextGuy ? -1 : 1;
      });
      console.table(oldest);
Enter fullscreen mode Exit fullscreen mode

This function compares the lastGuy age to nextGuy age to see which one of them is bigger than other. If it's true returns 1. If false it's return -1.

Reading MDN site about it, we see:

If we have this function format:

function compareFunction(x, y){
    if(x < y) return -1;
    if(x === y) return 0;
    if(x > y) return 1;
}
Enter fullscreen mode Exit fullscreen mode
  • x < y - it returns 1 and x is sorted to an index lower than of the y position. (x comes first than y).
  • x == y - it returns 0 and this element isn't moved of the current index position.
  • x > y - it returns -1 and x is sorted to an index greater than of the y position. (x comes first than y).

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

So first of all I learned that we can call querySelector() on any existing DOM element, it does always have to be docement. We can look inside of an existing element

Secondly since querySelector() returns a NodeList and not an array we can't use map() here, so first we convert the NodeList into an array. There are two ways to do this.

We wrap it in Array.from() function

const category = document.querySelector(".mw-category");
const links = Array.from(category.querySelectorAll("a"));
const de = links
.map((link) => link.textContent)
.filter((streeName) => streeName.includes("de"));
Enter fullscreen mode Exit fullscreen mode

or we can create an array using [] and use ES6 spread to spread every single item into the array.

const links = [...category.querySelectorAll("a")];
Enter fullscreen mode Exit fullscreen mode

Spread will take every item out of something iterable (here NodeList) and put in into the containing array.

  • Another sorting exercise Question: Sort the people alphabetically by last name

Now we here we do not use the initial array of objects provided to us rather we use this array

const people = [
        "Bernhard, Sandra",
        "Bethea, Erin",
        "Becker, Carl",
        "Bentsen, Lloyd",
        "Beckett, Samuel",
        "Blake, William",
        "Begin, Menachem",
        "Bellow, Saul",
        "Benchley, Robert",
        "Bent, Silas",
        "Berle, Milton",
        "Berry, Halle",
        "Biko, Steve",
        "Beck, Glenn",
        "Bergman, Ingmar",
      ];
Enter fullscreen mode Exit fullscreen mode

Now we do not have objects to work with here so to have proper variables to work with we first split the strings to convert them into firstName and lastName and the use array destructuring that is rather than returning an array we put them into their own variables.

const alpha = people.sort((lastOne, firstOne) => {
        const [aLast, aFirst] = lastOne.split(", ");
        const [bLast, bFirst] = firstOne.split(", ");
        return aLast > bLast ? 1 : -1;
      });
      console.log(alpha);
Enter fullscreen mode Exit fullscreen mode

-last one was a reduce() exercise
Question: Sum up the instances of each of these

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

Important thing here is unless we start with and empty object we'll not get the result but hardcoding for example {car:0} will be a very tough task so we leave the object empty but because of that we are not sure the key exists in the object or not so we would have to check and if of present we'll set the initial value to 0 and this way we can keep adding items to our array and it's key will be added to object without any issue.

const transportation = data.reduce(function (obj, item) {
        if (!obj[item]) {
          obj[item] = 0;
        }
        obj[item]++;
        return obj;
      }, {});
      console.log(transportation);
Enter fullscreen mode Exit fullscreen mode

GitHub repo:



Twitter

Linkedin

You can also do the challenge at javascript30
Thanks WesBos to share this with us! 😊💖

Discussion (6)

Collapse
rash123 profile image
RASHMI VERMA

Great

Collapse
cenacr007_harsh profile image
KUMAR HARSH Author

thanks a lot.

Collapse
kritebh profile image
Kritebh Lagan Bibhakar

console.table is like "Mjollnir"

Collapse
cenacr007_harsh profile image
KUMAR HARSH Author

yup once you've used it there is no going back lol

Collapse
rohitk570 profile image
ROHIT KUMAR

NICE WORK

Collapse
cenacr007_harsh profile image
KUMAR HARSH Author

thanks.