Understanding forEach, map, filter, and reduce in JavaScript
Learn how to manipulate arrays using these powerful array methods.
Array Methods Overview
JavaScript provides several built-in methods for working with arrays. Four of the most commonly used methods are forEach
, map
, filter
, and reduce
. Each of these methods serves a different purpose and can be used to perform various operations on array elements.
1. forEach
The forEach
method executes a provided function once for each array element. It does not return a new array and is primarily used for side effects, such as logging or modifying external variables.
let arr1 = [1, 2, 3, 4, 5, 6, 7];
arr1.forEach((item, i) => {
console.log(item, i);
});
This code logs each item in arr1
along with its index. The output will be:
- 1, 0
- 2, 1
- 3, 2
- 4, 3
- 5, 4
- 6, 5
- 7, 6
2. map
The map
method creates a new array populated with the results of calling a provided function on every element in the calling array. It is used when you want to transform the elements of an array.
let arr2 = arr1.map((item) => item * 2);
console.log(arr2);
This code creates a new array arr2
where each element is double the corresponding element in arr1
. The output will be:
[2, 4, 6, 8, 10, 12, 14]
3. filter
The filter
method creates a new array with all elements that pass the test implemented by the provided function. It is used to remove unwanted elements from an array.
let oddNumbers = arr1.filter((item) => item % 2 !== 0);
console.log(oddNumbers);
This code filters out even numbers from arr1
, returning only the odd numbers. The output will be:
[1, 3, 5, 7]
4. reduce
The reduce
method executes a reducer function on each element of the array, resulting in a single output value. It is often used for accumulating values or combining elements.
let sum = arr1.reduce((accumulator, item) => {
return accumulator + item;
}, 0);
console.log(sum)
This code sums all the elements in arr1
, starting from an initial value of 0. The output will be:
28
5. Custom myMap Function
The myMap
function mimics the behavior of the built-in map
method. It takes an array and a callback function as arguments, applies the callback to each element, and returns a new array with the results.
function myMap(array, callback) {
const newArray = []; // Create a new array to hold the results
for (let i = 0; i < array.length; i++) {
newArray.push(callback(array[i], i, array)); // Apply the callback and push the result
}
return newArray; // Return the new array
}
// Example usage
const numbers = [1, 2, 3, 4, 5];
const doubled = myMap(numbers, (num) => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
This function transforms each element of the array and returns a new array.
6. Custom myFilter Function
The myFilter
function works similarly to myMap
, but instead of transforming each element, it checks if each element meets a certain condition. If it does, the element is included in the new array.
function myFilter(array, callback) {
const newArray = []; // Create a new array to hold the filtered results
for (let i = 0; i < array.length; i++) {
if (callback(array[i], i, array)) { // Check if the element meets the condition
newArray.push(array[i]); // If true, add it to the new array
}
}
return newArray; // Return the new array
}
// Example usage
const evenNumbers = myFilter(numbers, (num) => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
This function filters the array based on a condition and returns a new array with only the elements that pass the test.
7. Custom myReduce Function
The myReduce
function processes each element of the array to accumulate a single output value. It uses an accumulator to keep track of the result as it iterates through the array.
function myReduce(array, callback, initialValue) {
let accumulator = initialValue !== undefined ? initialValue : array[0]; // Set the initial value
const startIndex = initialValue !== undefined ? 0 : 1; // Determine the starting index
for (let i = startIndex; i < array.length; i++) {
accumulator = callback(accumulator, array[i], i, array); // Update the accumulator
}
return accumulator; // Return the final accumulated value
}
// Example usage
const sum = myReduce(numbers, (acc, num) => acc + num, 0);
console.log(sum); // Output: 15
This function accumulates values from the array into a single output value.