This is from 43.25 on the first video and covers forEach()
, map()
and filter()
The syntax for these is the same:
arrayName.forEach((item)=> {
//some code...
});
forEach()
The forEach()
method is used to iterate through an array and outputs via a function.
This is an example of the syntax for a high order array method. With an array called myArray
it would be:
myArray.forEach(function(item){
console.log(item);
});
Here is the syntax using an arrow function:
myArray.forEach((item) => {
newP[0].innerHTML += `<div>${item}</div>`;
});
An even more abbreviated example:
myArray.forEach((item) => console.log(item));
NB. The word item could have been any valid JS variable name. Often the singular of the array name is used. For example in an array called dogs
then dog
could be used.
Second parameter
The forEach()
method can also take a second parameter. So the first parameter is the value of each array item the second paramenter is it’s index
or place number in the array, starting with 0 for the first array item.
outputs the array below and, using the forEach
loop, to the console.
You can also use it like so:
["Bilbo", "Gandalf", "Nazgul"].forEach(alert);
The buttons below use the code above but also using map
and filter
which makes no difference as set.
Use any function
You can also use any function with the forEach
method as a callback function as a parameter. For example if you want to use a function previouly declared and named myCoolFunction
then:
myArray.forEach(myCoolFunction);
You might want to use the value of each array item in this function so as before think of a variable name, like item
here, and add it as a parameter of the function:
myArray.forEach(myCoolFunction(item));
Some of the examples below use a JS object todos
…
View the todos object
const todos = [
{
id: 1,
text: 'Take out rubbish',
isCompleted: true,
},
{
id: 2,
text: 'Meet with boss',
isCompleted: true,
},
{
id: 3,
text: 'Dental appointment',
isCompleted: false,
}
];
map()
The map()
method is extremely similar to forEach()
. The key difference is that map()
creates a new array.
This means you can store the result of map()
in a variable whereas you can’t with forEach()
let myNames = ['Bob', 'Johan', 'Tobble', 'Snod', 'Trouser' ]
let forEachNames = myNames.forEach(name => {name.toLowerCase()} );
console.log(forEachNames);
// undefined
let mapNames = myNames.map( name => name.toLowerCase() );
console.log(mapNames);
// [ 'Bob', 'Johan', 'Tobble', 'Snod', 'Trouser' ]
The map()
method allows you to map each item in an array to something else.
In this example each element is mapped to <li>
tags:
const viverrids = ['oyan', 'civit', 'gennet', 'binturong'];
const vivListItems = viverrids.map(animal => '<li>' + animal + '</li>');
// to add outer ul tags you might use join()...
const finalCode = '<ul>' + vivListItems.join('') + '<ul>';
The map
method creates a new array from an array. It therefore makes sense to store the output in a new variable.
Here it is used on an array of objects (todos
) to get all the values of text
and store them in a new array called todosText.
const todoText = todos.map((item) => {
return item.text
});
console.log(todoText);
filter()
The filter
method also creates a new array, this time based on a condition.
OR it creates a new array of items from an array that pass a given test. A function can be used as a parameter for the test.
const todoCompleted = todos.filter(function(todo) {
return todo.isCompleted === true;
});
console.log(todoCompleted);
Chaining multiple array methods together
It’s also possible to chain several of these together.
const todoCompleted = todos.filter(function(todo) {
return todo.isCompleted === true;
});.map(function(todo){
return todo.txt;
})
Links
More on filters in the Traversy Media video at 45 mins as well as a whole video on high order array methods.
A full list of array methods, all time stamped so easily searchable, is portEXE’s video: