Wes Bos Project 4 - Key Concepts (JS)

Wes Bos Project 4 - Key Concepts (JS)

Wes Bos JS30 is an awesome way to learn JS by doing projects. Here is the link to all my solutions:- here

Project 4 is completely based on the Arrays and how to use some prototyping methods attached under Array.prototype.method()

1. Filter:-

One of the easiest ES6 prototyping method of all! The generalized way of writing it is:- {ArrayName}.filter(iterator => {condition for new array output}).

For the solution in Wesbos this is the code I used to filter out the arrays that were born in the 1500s:-

 console.log(inventors.filter(inventor => inventor.year < 1600 && inventor.year >= 1500));

2. Map:-

I felt this also an easy way to iterate over all the elements and do some operation on them rather them filtering out as in previous. The generalized way of writing it is:- {ArrayName}.map(iterator => {condition on the element for new array output})

For the solution in WesBos this is the code I used to join each first name and last name in the array of objects:-

console.log(inventors.map(inventor => inventor.first + ' ' + inventor.last));

3. Sort:-

Now, this might seem too easy but can get tough if some condition is to be employed to sort the array. The generalized way of writing it is:- {ArrayName}.sort(function(parameters) {comparing function -> executed if true or not})

To make it more clear I will write down the code where we want to sort the array from oldest to youngest.

const fi = inventors.sort(function(a,b) {
      const ans = a.year > b.year ? 1 : -1; 
      return ans
    });
    console.table(fi)

See the generalized code and compare it with the above code and see how it goes!

4. Reduce:-

This is literally tricky if you don't know much about reduce. Mostly used to sum over different conditions. The generalized code goes like this- {ArrayName}.reduce((variable, iterator)=>{add to the variable as per iterator wants}, starting point of variable)

Now let's say I want to find the total year all the people in total were alive given their born and passing year.

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

Try to map the generalized code with the code above and you can see the similarity.

This is it. Learned four main concepts

  1. Map
  2. Reduce
  3. Filter
  4. Sort