Working with arrays in JavaScript used to be really annoying and complex. Fortunately now, there are a bunch of amazing JavaScript array methods that just make life easier. In this post, I will be covering the 5 most important JavaScript array iteration methods.
.forEach
This is a fundamental array method concept. If you can understand how this one works, you're gonna be able to learn the other methods a lot more easily.
This method is basically a for loop that takes in a function with a parameter and outputs that same data.
For example:
const array = ['a', 'b', 'c'];
array.forEach(letter => {
console.log(letter);
});
// expected output: "a"
// expected output: "b"
// expected output: "c"
.map
This method is also really simple. It allows you to take one array as a parameter and convert it into a new array. You'll find yourself using this method a lot.
For example:
var array = [1, 4, 9, 16];
// pass a function to map
const map = array.map(x => x * 2);
console.log(map);
// expected output: Array [2, 8, 18, 32]
.find
This allows you to find a single object within an array. It takes in a parameter and returns the first element in the array that returns true.
For example:
var array1 = [5, 12, 8, 130, 44];
var found = array1.find(function(element) {
return element > 10;
});
console.log(found);
// expected output: 12
.reduce
This method operates on an array, and reduces it to a single value.
It takes in two arguments:
-
A callback function with 2 parameters:
- accumulator: the starting value
- currentValue: each element in the array
The initial value for the accumulator.
The return function is then stored in the accumulator.
For example:
const array = [1, 2, 3, 4];
const reduce = array.reduce((accumulator, currentValue) => {
accumulator + currentValue;
}, 0);
// 1 + 2 + 3 + 4
console.log(reduce);
// expected output: 10
Top comments (0)