Arrays and iterators
Last time we looked at how to use a for loop to run through a list (array) and have each array element displayed in a specific way - but there are other ways to do so when our elements are stored in an array as arrays have some built in methods that can help us loop through them. We will look at some of these methods today.
The .forEach() method
The .forEach() method will execute the same code for each element of an array. The method takes a callback function as argument. During each execution, the current element is passed as an argument to the callback function.
In the example above, the sentence "You need to buy ..." will be logged 3 times in the console, displaying all the items in our shopping list.
Example 2 of the .forEach method
In the following example, instead of using an arrow function, we define the function beforehand and use it as the callback function.
As in the previous example the .foreach method takes a function as argument - in this case, the function called is the function logItems.
The .map() method
The .map() method also takes an argument of a call function, but returns a new array.
Example of the .map() method in use
In the example above, we use the .map() method to convert fahrenheit to celcius. Each degree in the fahrenheit array is converted into celcius by taking the value - 32 / 1.8000 which as far as I know, is the calculation used to convert fahrenheit to celcius. Correct me, if I'm wrong.
Our new array (celcius) will contain the same number of elements as our initial array (fahrenheit).
The .filter() method
Like the .map() method, the .filter() method takes a function as argument and returns a new list.
The callback function for the .filter() method returns a boolean value (true or false). The elements from the original list (array) that returns true is added to the new list, while the elements that return false is filtered.
Example of the .filter() method in use
In this example, the .filter method iterates through our shopping list (shoppingList) and looks for all the array elements that start with the letter b.
The .reduce() method
The .reduce() method returns a single value after iterating through the array.
Example of the .reduce() method in use
The method takes a callback function as argument. In the example above, the callback function takes two parametres: accumulator and currentValue. The value of accumulator is initially equal to the value of the first array element - score -, meaning 1, while currentValue is equal to the value of score, meaning 0. As 1 + 0 is equal to 1, the value of accumulator is still 1, when the program continues to the next array element, while the value of currentValue changes to that of score, meaning 1.
The method iterates through the entire list and then returns a single value, being the sum of all the numbers in the array - in this case, 3 (1 + 0 + 1 + 0 + 0 + 0 + 1).
NB: The method can be used to iterate through array that contain other data types as well.