JavaScript .forEach() for Array Iteration
The .forEach() Method
The .forEach() method is an array method that takes a callback function as an argument. It iterates through the elements in the array and executes the callback function on each element. The callback function can be defined as a function expression, an arrow function or a reference to a function. The syntax for .forEach() with an arrow function is as follows:
The syntax for .forEach()
array.forEach((element) => {
// do something with element
});
Iterating Over an Array with .forEach()
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
/*
OUTPUT
1
2
3
4
5
*/
Or you could do it with the .forEach() method like this:
`let numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => console.log(number));
/*
OUTPUT
1
2
3
4
5
*/`
Arguments of the .forEach() Callback Function
The callback function that you pass to the .forEach() method can take up to three arguments. The first argument is the current element in the array. The second argument is the index of the current element. The third argument is the array itself:
array.forEach((element, index, array) => {
// do something with element, index, and array
});
The arguments are as follows:
- element: The current element in the array
- index: The index of the current element
- array: The array itself
*JavaScript Map Array Method *
The .map() method effectively "maps" the values to a new array.
When to Use the Map Method
A map, in programming terms, is a transformation of values. The .map() method is a way for you to say, "transform each value according to my instructions". Maybe you want to double each value in the list? With .map(), it's straightforward:
const values = [1, 2, 3, 4, 5];
values. map((value) => value * 2); // [2, 4, 6, 8, 10]
Arguments to the .map() Callback
Like many array methods, the callback accepts more arguments than just the element in the array. With .map() it calls the callback with the element, index, and original array.
const values = [1, 2, 3, 4, 5];
values.map((value, index, array) => {
console.log(value, index, array);
});
// 1 0 [ 1, 2, 3, 4, 5 ]
// 2 1 [ 1, 2, 3, 4, 5 ]
// 3 2 [ 1, 2, 3, 4, 5 ]
// 4 3 [ 1, 2, 3, 4, 5 ]
// 5 4 [ 1, 2, 3, 4, 5 ]
What is Flattening?
Flattening refers to the process of converting a multidimensional array (an array that contains other arrays) into a single-dimensional array. This means taking all the nested elements and bringing them up one level in the hierarchy.
For example, if you have the following array:
const nestedArray = [1, 2, [3, 4, [5, 6]]];
Flattening this array would result in:
const flatArray = [1, 2, 3, 4, 5, 6];
Top comments (0)