JavaScript

Iteration methods

We have talked about DOM nodes and now we will talk about iterators.
Normally you talk about this with arrays, because this is array methods.
There are other ways to loop through our elements when sre stored in an array. They have some built in methods that can help us loop through them.
There are more than I am showing you.

The .forEach() method

array.forEach(function(currentValue, index, arr));

The forEach() method calls a function once for each element in an array, in order.
The currentValue is required. It is the value of the current element. Index is optional. It is the array index of the current element. arr is optional. It is the array object the current element belongs to.

Explain an example

let superheros = ["Batman", "Superman", "Iron man", "Thor", "Hulk"];
superheros.forEach(element => console.log(element + " is a superhero"));

In the example above, the superheroes name will be printet out 3 times (because we have three elements in the array).

let shoppingList = ["milk", "carrots", "bananas"];
function logItems(item) {
console.log("You need " + item);
}
shoppingList.forEach(logItems);

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

arr.map(callback(currentValue[, index[, array]]);

This method returns a new array with the updated elements after calling a callback function on every element in the array.

Explain an example

let fahrenheit = [32, 41, 50, 59, 68];
let celcius = fahrenheit.map(number => {
return number - 32 / 1.8000;
})
console.log(celcius);

We have an array where we use the .map method. Which will update every element after a callback function. We will update it with from fahrenheit to celcius.

let ages = [32, 41, 50, 59, 68];
let oneYear = ages.map(number => {
return number + 1;
});
console.log(oneYear);

There have updated the array ages with 1 because every year you are getting older. In the new array should the numbers be updated with one.

The .filter() method

let newArray = arr.filter(callback(currentValue[, index[, array]]);

This method checks each element in an array to see if it meets a condition. It returns a new array with the elements that meet the condition.

Explain an example

superheros = ["Batman", "Superman", "Ironman", "Hulk"];
let shortSuperheroes = superheros.filter((person) => {
return person.length < 7
});
console.log(shortSuperheroes);

The .filter() method should return true or false depending on if the element length is shorter than 7. If the elements return true are they added to the new array.

shoppingList = ["milk", "carrots", "bananas", "beans", "cucumber", "tomatoes"];
let startsWithB = shoppingList.filter((element) => {
return element.startsWith("b");
});
console.log(startsWithB);

.filter method iterates through our shoppingList and looks for all the array elements that start with the letter b.

The .reduce() method

arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue]);

The reduce method is used to reduce the array to a single value. The method subtract the numbers in the array, starting from the left.

Explain an example

let score = [1, 0, 1, 0, 0, 0, 1];
let finalScore = score.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
});
console.log(finalScore);

The function has 2 parametres: accumulator and currentValue. The value of accumulator is initially equal to the value of the first array element score[0], meaning 1, while currentValue is equal to the value of score[1], 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[2], 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).

let numbers = [175, 50, 25];
let scores = numbers.reduce((total, num) => {
return total - num;
});
console.log(scores);

The function has 2 parametres: total and num. The value of is equal to the first array numbers[0] meaning 175, while num is equal to the value of score[1], meaning 50. The value of total is 125 ( 175-50 ). The value of total is 125, when the program continues to the next array element. 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, 100 (175 - 50 - 25).

Image filter

See the Pen Filter images by Dominoeffekten (@dominoeffekten) on CodePen.

Explained code

const imgs = Array.from(document.getElementsByClassName("filter"));

We have made a variable which containes an array based on the class names filter

const buttons = Array.from(document.getElementsByTagName("button"));

We have declared a variable that stores an array of all button elements

const btnClicked = (e) => {
buttons.forEach(button => {
button.removeAttribute("class");
})
e.srcElement.classList.add("active");
filterFunc(e.srcElement.id);
}

Declaring a function using the arrow syntax that 1) iterates through the array of buttons removing the class attribute, 2) adds the class active to the source element that triggered the function and 3) calls the filterFunc function, passing the id of the element that triggered the function as argument.

const filterFunc = (category) => {
imgs.forEach((img) => {
img.style.display = "none";
})

let filter = imgs.filter((img) => {
return img.classList.value.includes(category);
})

filter.forEach((img) => {
img.style.display = "grid";
})
}

Declaring a function using the arrow syntax that 1) iterates through the array of elements with class name filter and when doing so changes the value of the display property to none, 2) declares a new variable that stores an array of the elements from the imgs variable, whos class list include the value matching the id of the element clicked, and 3) makes the elements contained in the new array display grid.

buttons.forEach(button => {
button.addEventListener("click", btnClicked);
})

Iterating through the array of buttons, adding an event listener to each of them that calls the btnClicked function.