JavaScript 30 Day 4 Study Notes
In this lesson, Wes Bos worked through several array methods; filter, map, sort, and reduce. I am not too familiar with using these methods so I followed the video and coded along with Bos as he ran through 8 exercises using these methods.
Filter
The textbook, Eloquent JavaScript, defines the filter method as such, “It filters out the elements in an array that don’t pass a test…”
For an array of objects containing data regarding inventors. This method filters out inventors born on or after 1800.
const eighteen = inventors.filter(inventor => (inventor.year >= 1800));
A new array is created with elements that pass the test.
Map
Eloquent JavaScript states, “The map method transforms an array by applying a function to all of its elements and building a new array from the returned values.”
To list the inventors’ full names, Bos wrote the following.
const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`);
This creates a new array containing their first and last names. Once again, I saw template literals being used.
Sort
The sort method loops through the array and sorts the elements into the desired order.
const ageOrder = inventors.sort((a,b) => a.yearOfBirth > b.yearOfBirth ? -1 : 1);
As the method goes through and tests a pair of elements, it orders them using a plus one or minus one increment.
Reduce
The reduce method loops through the array and computes a single value. Although this sounds simple, I found it the most difficult of the four array methods covered in the lesson.
const totalYears = inventors.reduce((total,inventor) => {return total + (inventor.passed - inventor.year);},0);
The method produces a single number representing the total.
Passing the “total” variable through a function presented some difficulties for me. Having to set the total variable to zero is a new concept for me.
Bos recommended working through many repetitions of these exercises to get more familiar with them. After coding along with him the first day, I went back the next day and worked through the exercises, changing the data to make it different.
View my notes from the beginning.
View my notes from Day 5.