Array Cardio (1)
Check the console for the array results. Below is a few notes on some of the methods.
.filter()
The filter() method will create a new array with all elements that pass the test implemented by the provided function.
Filter works by passing it a function which will loop over every single item in the array and decide whether or not to keep it.
In example 1 we pass in 'inventor' as the name we give each item that has been looped over.
We can then carry out some logic, hence if inventor.year greater than something return true. This will keep the instances of 'inventor' that pass that check. We can then console.table the result for easier reading.
.map()
The map() method takes and array, does something with it and returns a new array with the same length.
.map() will always return the same amount of items as you give it. Filter doesn't. Filter can take in 10 things and return 2.
In example 2, we loop through the inventors and create a new array with just the first and last names.
.sort()
The sort() method takes does what it says on the tin and sorts things in a particular order.
In example 3 we specify a function and pass in a and b (this can be anything i.e. firstPerson and secondPerson but many people use a and b for ease).
We next create some logic that says if a.year is greater than b.year return 1 else return -1. This basically moves the people/data up and down within the array.
.reduce()
The reduce() method takes and array and returns a single value.
In example 4 we loop over the inventors, passing in total and inventor to the function.
The total is referring to the actual total each time the loop runs.
A simple example is:
const numbersArray = [1, 2, 3, 4];
const total = (accumulator, currentValue) => accumulator + currentValue;
console.log(numbersArray.reduce(total));
// this should give us an output of 10
Here, accumulator will start at 0 and each loop currentValue in the array will be added until all values have been used and we should be left with the value 10.