Array Methods: forEach, map, filter, find
In this lesson, we will introduce four methods used to iterate over array elements: forEach
, map
, filter
, and find
.
forEach
forEach
executes a provided function once for each array element.
For example, using forEach
, you can sequentially log all items in an array.
const fruits = ['Apple', 'Banana', 'Cherry'];
fruits.forEach(function (fruit) {
console.log(fruit);
});
map
map
applies a given function to each array element and returns a new array with the results.
For example, using map
, you can double all the numbers in an array.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function (num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6, 8]
filter
filter
creates a new array with all elements that pass a test implemented by the provided function.
For example, using filter
, you can select only the even numbers from an array.
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(function (num) {
return num % 2 === 0;
});
console.log(evens); // [2, 4]
find
find
returns the first element in the array that satisfies the provided testing function.
If no elements satisfy the testing function, undefined
is returned.
For example, using find
, you can locate the first number greater than 10 in an array.
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(function (num) {
return num > 10;
});
console.log(found); // 12
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.