Foreach, Map, Filter, Reduce
Foreach, Map, Filter, Reduce
Introduction to forEach.
Earlier whenever there was a necessity of iterating over arrays, developers majorly used for loops. But, using
loops can sometimes be slow and error-prone when we deal with large complex arrays. So, forEach was
standardized with the release of ECMAScript 5 (ES5) in 2009.
The introduction of the forEach() method in ES5 provided a more convenient and efficient way to iterate over
the elements of an array. It allowed developers to perform a specific function on each element of an array
without having to manually write for a loop. One more thing to note is that within forEach we cannot use the
loop control statements such as break, and continue.
callbackFunction: This argument contains the method that will be called for each array element. It is a
mandatory parameter
index: This parameter is optional and contains the index number of each element
array: This parameter is optional and contains the entire array on which the method is being applied.
Implementation
Let’s imagine you are assigned a task to display all the items added to the cart in an e-commerce application.
You can do it in multiple ways but let’s assume we are asked to do it using forEach.
let itemsInCart = [
"apple",
"comb",
"mike",
"keyboard",
"t-shirt",
"mobile holder",
];
Output:
/* OUTPUT :
apple
comb
mike
keyboard
t-shirt
mobile holder
*/
console.log(
index + 1
);
/*
OUTPUT:
The item apple was added to cart in position 1. The items in cart
are apple,comb,mike,keyboard,t-shirt,mobile holder.
The item comb was added to cart in position 2. The items in cart
are apple,comb,mike,keyboard,t-shirt,mobile holder.
The item mike was added to cart in position 3. The items in cart
are apple,comb,mike,keyboard,t-shirt,mobile holder.
The item t-shirt was added to cart in position 5. The items in cart
are apple,comb,mike,keyboard,t-shirt,mobile holder.
The item mobile holder was added to cart in position 6. The items
in cart are apple,comb,mike,keyboard,t-shirt,mobile holder.
*/
In this case, for each element in the itemsInCart array, the function will log a string to the console. The string
includes the current item, its index (incremented by 1 as the indexing starts from 0, to make it
The map method of the array takes a function as a parameter and returns a new array that contains the result
of the function performed on each array item. Hence, the new array would be of the same length.
The map() method is used over other iterative methods such as for loops or forEach() based on the
applications. map() allows us to easily operate on the array items. It returns a new array containing the result of
these operations. As it creates a new array, the array on which the map method is applied would be unaltered
Syntax:
Function declaration
Arrow Function
Callback Function.
// Function Declaration
// Arrow Function
array.map(callback)
item: It is a required parameter and it holds the value of the current item in the iteration
index: It is an optional parameter and it holds the index of the current item in the iteration
The return value is a new array whose items are the result of the function performed on each array item.
Implementation
Let’s now look at a use case of the map method. Imagine you are working at an e-commerce site. Imagine the
website is storing the price as strings and you are assigned a task to convert all the prices in the cart to
"205"];
=> {
return Number(item)
);
console.log(cartItemsPriceAsNumbers);
// OUTPUT
The above example has an array "cartItemsPriceAsStrings" that contains the prices of items as strings. We will
use the map method over that array. Using the "Number()" function to convert each string to a number. The
result of each iteration on array items is assigned to a new array called "cartItemsPriceAsNumbers"
Note: If you forget to return a value within the callback function of the “map” method in JavaScript, the resulting
array will contain undefined values in the corresponding positions. This happens because “map” creates a new
array by applying the callback function to each element of the original array and uses the returned value to
application, we use filtering. We filter the products in a shopping site based on criteria, we filter the posts on any
social media based on the date posted or based on the keywords. So, filtering the data is one of the important
task.
The filter method is used to create a new array whose items are the result of the filtering criteria of the original
array. Only those values which satisfy the given criteria are added to a new array, and that array is returned.
Whenever the filter method is applied to an array, we pass a filter function to it. The filter function iterates over
all the elements of the given array and passes each element to the callback function. If the callback function
returns true, then the element is added to the result array otherwise it is ignored.
Syntax:
The callback function can be passed to the filter function in the following ways:
Function declaration
Arrow Function
Callback Function.
// Function Declaration
// Arrow Function
array.filter(callback)
item: It is a required parameter and it holds the value of the current item in the iteration
index: It is an optional parameter and it holds the index of the current item in the iteration
The filter function returns an array. if the callback function returns truthy, element is added in the output array
and if the callback function returns falsy, then that element is removed in the output array. It does not affects
The filter() method creates a new array “longUserNames” by filtering out the names with a length greater than
or equal to 5.
The filter() method iterates through each element in the userNames array, and for each element, it calls the
provided function ((item) => item.length > 5) with the element as the argument.
If the function returns true for that element (if the length of the name is greater than 5), it is included in the
longUserNames array, otherwise, it is excluded.
The “break” keyword does not work in the forEach, map, and filter methods in JavaScript like it does in traditional
loops such as for or while loops. The “forEach”, “map”, and “filter” methods are higher-order functions that
operate on arrays and execute a provided callback function for each element. These methods do not provide a
direct mechanism for breaking out of the iteration process. So these methods have their own internal control
flow, and the iteration behavior is predefined.
If we write “break” keyword along with “forEach”, “map”, or “filter”, it will throw us Syntax error
// Using forEach
numbers.forEach(number => {
if (number === 3) {
console.log(number);
});
// Using map
if (number === 3) {
return number * 2;
});
// Using filter
if (number === 3) {
return true;
});
Introduction
As the name suggests the reduce method reduces the array values to a single value. The reduce() method
runs a reducer function on each array item and returns a single output result. The input array can have
numbers, strings, or an object.
Features of reduce
1. The reducer function passed will be applied to all the items in the array.
2. The result will be a single value accumulated on passing all the array items to the reducer function.
4. The reduce method doesn’t change the original array on which the reduce method is applied.
Syntax:
2. currentValue: It is a required parameter and is used to specify the value of the current element.
3. currentIndex: It is an optional parameter and is used to specify the array index of the current element.
4. array: It is an optional parameter and is used to specify the array the current element belongs to.
5. initialValue: It is used to specify the value to be passed to the function as the initial value. It’s optional.
Implementation
Let’s look at the implementation of the reduce method. The simplest example to demonstrate the use of reduce
function is by finding the sum of all elements in an array.
// Given Array
console.log(result);
// output
203
We are passing in a callback function as the reduce function (acc, curr) => acc + curr, which takes in the
accumulator and current value as arguments, and adds the current value to the accumulator. We have also
passed in the initial value as 0, which is the starting value of the accumulator.
Note: If the initial value is not passed to the reduce method, the first item in the sequence is used as the initial
value and the operation starts from the second item in the sequence. If the sequence is empty, a TypeError is
raised.
// Given Array
console.log(result);
// output
10
Example2:
});
The reduce method iterates through the array and for each element, it applies the callback function and
updates the accumulator, adding the current value to the accumulator and storing the result in the
accumulator.
After iterating through the entire array, the final value of the accumulator is returned, which is the sum of all
elements in the array.
Now lets have a look at how we can use reduce function on an array of objects
];
return student;
} else {
return acc;
});
In this example, we have an array of student objects, where each object contains the properties name and
score. We use the reduce method to find the student with the highest score in the array.
The callback function passed to reduce takes two arguments: acc (accumulator) and student (current object
in the iteration). In this case, the accumulator initially holds the first student object in the array.
In each iteration, the callback function compares the score of the current student with the score of the
accumulator. If the score of the current student is higher, the current student object is returned and becomes
the new accumulator. Otherwise, the accumulator remains unchanged.
Interview Points
Implement a JavaScript function that uses the filter method to extract only the even numbers from an array.
Provide an example array and demonstrate the use of your function.
Ans.
function filterEvenNumbers(arr) {
forEach vs map
Imagine you have an array of objects representing products and need to extract an array of just the
product names. Here's where the map can be advantageous:
const products = [
];
In this scenario, the map is advantageous because it allows you to create a new array containing only the
product names in a concise and readable manner. If you were to use forEach for the same task, you would
need to declare an empty array, push each product name into it, and manage the array manually. map
simplifies this process by handling the creation of the new array for you.