JavaScript Array Methods Detailed Review of forEach() ,map , filter() and reduce()

Search for a command to run...

No comments yet. Be the first to comment.
π‘ βSo if you want to go fast, if you want to get done quickly, if you want your code to be easy to write, make it easy to read.β -By Robert C. Martin JavaScript has progressed a ton in recent years. If you are learning JavaScript in 2022 and you ...

Before beginning our quest to find how not to use Create React App. First, letβs see why we need Create React App in the first place. Why do we need Create React App? π€ Create React App is a comfortable environment for learning React and is the best...

Getting Started with Node.js In this blog, we will try to understand the basics of Node.js, how it works, and why to choose Node.js, but before diving into node let's talk a little bit about Java-script. JavaScript is one of the best programming lang...

If you are reading this, you probably know what React.js is and might have already used it Earlier. However, you might be wondering why I am reading about folder structure? Canβt I just stuff all my files in the src folder?? π€ͺ Technically you could ...

Quoting from MDN directly.
The
Arrayobject, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name and has members for performing common array operations.
For example see this sample of code of JS
// 'kings' array created using array literal notation.
const kings = ['Ashoka', 'Samundragupta'];
console.log(kings.length);
// 2
forEach() Method πIf for loop is a jack of all trades in looping over an array. And you hate having to iterate using index wishing if only there were easier ways.
forEach() is for the answer for you, it is a master of simplicity and easily understood code.
forEach() using arrow function.forEach((element, index, array) => { /* ... */ })
callbackFn : Function which executes on each elementelement : Current element being worked on in array.index (Optional) : The index of element in arrayarray (Optional) : Array upon which forEach() was called .const arr=[
{
'name':'Aashirwad',
'roll':4
},
{
'name':'Pankaj',
'roll':78
},
{
'name':'Ayush',
'roll':70
},
{
'name':'Nisha',
'roll':33
},
]
arr.forEach(element => console.log(element));
//
// { name: 'Aashirwad', roll: 4 },
// { name: 'Pankaj', roll: 78 },
// { name: 'Ayush', roll: 70 },
// { name: 'Nisha', roll: 33 }
//
forEach() πforEach() π₯²callbackFn could.forEach() loop ( like using break or return in for loop)const wars = [2, 8, 5];
let sum = 0;
const sumWarFunction = async (a, b) => a + b;
wars.forEach(async (war) => {
sum = await sumWarFunction(sum, war);
});
console.log(sum);
// Naively expected output: 18
// Actual output: 0
If forEach() was master of simplicity for looping over array.
map is the king of modifying the array. If you want to simply modify the content of the array in an easily debuggable and readable code map is the answer for this.
map((element, index, array) => { /* ... */ })
callbackFn: Function which executes on each element and each time callbackFn is called returned value is added to the newArrayelement: Current element being worked on in array.index (optional): The index of element in arrayarray (optional): Array upon which map was called.Return value :
A new array is returned with each element being the result of a callback function.
const arr=[
{
'name':'Aashirwad',
'roll':4
},
{
'name':'Pankaj',
'roll':78
},
{
'name':'Ayush',
'roll':70
},
{
'name':'Nisha',
'roll':33
},
]
const map1 = arr.map(x => x.roll * 2);
console.log(map1)
// [
// { name: 'Aashirwad', roll: 8 },
// { name: 'Pankaj', roll: 146 },
// { name: 'Ayush', roll: 140 },
// { name: 'Nisha', roll: 66 }
// ]
Here we see that map is used not just to iterate over array but also the element of the array is modified in such a way that value is returned to a newArray.
map πͺ (Pros over forEach())newArray they are chainable.map π₯² (Cons)forEach() is better.It takes in a callback function with array element and returns a new array with operation defined in return statement used during the function call.
const arr=[
{
'name':'Aashirwad',
'roll':4
},
{
'name':'Pankaj',
'roll':78
},
{
'name':'Ayush',
'roll':70
},
{
'name':'Nisha',
'roll':33
},
]
let mymap =(ar,callback)=>{
const new_ar=[];
ar.forEach((e) => {
new_ar.push(callback(e))
});
return new_ar;
}
console.log(mymap(arr,(a)=>{
return a.name
}))
// [ 'Aashirwad', 'Pankaj', 'Ayush', 'Nisha' ]
filter() method π₯³filter() is a kind of Mantri ( minister ) for kings, filtering out the elements before returning them in a newArray based on callbackFn returning only those values which satisfy a condition.
filter() using arrow function.filter((element, index, array) => { /* ... */ } )
callbackFn: Function is to test each element of the array and return a value that is either true to keep the element in newArray or false to not keep the element in the newArray.element: Current element being worked on in array.index (optional) : The index of element in arrayarray (optional) : Array upon which filter() was called .Return value :
A new array is returned elements that pass the test defined in callbackFn.
filter() methodconst arr=[
{
'name':'Aashirwad',
'roll':4
},
{
'name':'Pankaj',
'roll':78
},
{
'name':'Ayush',
'roll':70
},
{
'name':'Nisha',
'roll':33
},
]
console.log(arr.filter(e => e.roll<20))
// [ { name: 'Aashirwad', roll: 4 } ]
Here we display only those elements on the console for which roll > 20. Thus filtering out other values.
filter() π«filter() π₯²filter() from scratch πconst arr=[
{
'name':'Aashirwad',
'roll':4
},
{
'name':'Pankaj',
'roll':78
},
{
'name':'Ayush',
'roll':70
},
{
'name':'Nisha',
'roll':33
},
]
const myfilter= function(arr,callback){
const filter_arr=[];
arr.forEach((e)=>{
if(callback(e)){
filter_arr.push(e);
}
})
return filter_arr;
}
console.log(myfilter(arr,(e)=>{
return e.roll>4
}))
// [
// { name: 'Pankaj', roll: 78 },
// { name: 'Ayush', roll: 70 },
// { name: 'Nisha', roll: 33 }
// ]
reduce() method π₯³reduce() is like the ministry of a King. It executes a user-supplied βreducerβ callback function on each element of the array, passing in return value after calculation and the final result is the single value after running the reducer across all elements of the array.
reduce() using arrow function.reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)
callbackFn : Reducer Function which takes in four argumentspreviousValue: initially this takes the initialValue or value of array[0]. Otherwise, it takes results from the value returned by the callbackFn in the previous call.currentValue : Value of the current element. On the first call, if initialValue is specified then array[0] or else it takes array[1].currentIndex : index position of the currentValue.initialValue (optional): Value which is to be given to previous on the first call.Return value :
A new value is returned which results from applying callbackFn over the entire array.
reduce() methodconst arr=[
{
'name':'Aashirwad',
'roll':4
},
{
'name':'Pankaj',
'roll':78
},
{
'name':'Ayush',
'roll':70
},
{
'name':'Nisha',
'roll':33
},
]
console.log(arr.reduce((previous,current)=>{
return previous+current.roll
},0))
//185
Here we display only those elements on the console for which roll > 20. Thus filtering out other values.
reduce() π€reduce() π₯²reduce() from scratch πSo in the below example sum of all roll numbers we pass in a second value alongside callback function to use as the first value of previous.
const arr=[
{
'name':'Aashirwad',
'roll':4
},
{
'name':'Pankaj',
'roll':78
},
{
'name':'Ayush',
'roll':70
},
{
'name':'Nisha',
'roll':33
},
]
let myreduce = function(arr,callback,initial){
let acc =initial || 0;
arr.forEach((e,i)=>{
acc=callback(acc,arr[i])
})
return acc;
}
console.log(myreduce(arr,(previous,current)=>{
return previous*current.roll
},1))
// 720720
forEach() Method
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
map method
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
filter() method
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
reduce() Method
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce