JavaScript Array Methods Map, Reduce, Filter
Let us now try to see how JavaScript array methods Map, Reduce, and Filter work. The code snippets are shown below:
To practice this tutorial, you need to have Visual Studio Code and NodeJS installed on your computer
We will start by seeing the basic functionalities of the JavaScript array and then we will further use map, reduce, and filter methods to perform some actions on the array.
The first step we need to take is to define an array with name ‘marks’
// defining the size of the array object
let marks = Array(6)
// populating the array with constructor method
marks = new Array(23,33,52,64,77.5,100)
In this step, we defined an array with identifier marks with a size of six elements and then we populated the array with some values separated by commas.
In the second step, we will perform some basic array functionalities like push, pop, and unshift and we will also see how we can traverse the array with for loop.
console.log('Marks: ' + marks) // this will display the array elements in console
marks.push(85) // This method will append an element at the end of the array
// Displays the new element pushed at the end of the marks array
console.log('Marks: ' + marks)
// This step will show you how to traverse in array with for loop
for (let i=0; i<marks.length;i++){
console.log(marks[i])
}
console.log("++++++++++++++++++++POP & UNSHIFT Elements in the array++++++++++++++++++++++")
marks.pop() // pop method removes last element from the array
console.log('Marks elements after deleting last elements from the array: ' + marks)
marks.unshift(120) // unshift method adds the new element at the start of the array
console.log('Marks elements after adding an element at the start of the array: ' + marks)
There is an array method that helps you to validate if an element is present in it.
console.log("++++++++++++++++++++ How to Validate element in the array++++++++++++++++++++++")
console.log("Is element present in the array: " + marks.includes(120)) /* This method will return boolean value i.e. true or false */
So these were some basic array functionalities that we discussed. Now I will show you examples of performing actions on array elements with and without the JavaScript reduce method. First, we will see if we need to sum the array elements without reduce method see the following code snippet
let totalMarks =0
for (let i=0; i<marks.length;i++){
totalMarks = totalMarks + marks[i] }
console.log(marks) // this will display the whole array in console
console.log(“Sum of marks array =” + totalMarks)
Second I will show you how we can simplify the above code snippet with the help of the JavaScript reduce method, see the following code snippet
console.log("++++++++++++ Array reduce method without using for loop ++++++++++++")
let total = marks.reduce((sum, individualMark)=>sum+individualMark,0)
console.log("Total Marks: " + total)
The following section explains how the JavaScript reduce method works
(method) Array<any>.reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue: any): any (+2 overloads)
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@param callbackfn — A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
@param initialValue — If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
The first argument is the callback function: We used only the first two arguments in our callback anonymous function i.e. <previousValue: sum>, <currentValue: individualMark>
The second argument is initial value: We used initialValue as <0> as our second argument in our reduced method call
Similarly, I will show you how JavaScript Filter and Map methods usage without using for loop
console.log("++++++++++++ Array Filter method without using for loop ++++++++++++")
let scores = [1,2,3,4,5,6,7,8,9,10]
let evenScores = scores.filter(score=>score%2==0)
console.log(evenScores)
console.log("++++++++++++ Array Map method without using for loop ++++++++++++")
let mappedValues = evenScores.map(score=>score*3)
console.log(mappedValues)
The following sections explain how the Filter and Map method work
(method) Array<number>.filter(predicate: (value: number, index: number, array: number[]) => unknown, thisArg?: any): number[] (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.
@param predicate — A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
@param thisArg — An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
So as it is defined with its method name Filter, this method is used to filter array elements based upon some condition specified in a callback function which we are passing as an argument to it. In our case, we used a predicate callback function that did not take any argument to filter out <evenScores> from the scores array and will return the elements of an array as an array. Output [2, 4, 6, 8, 10]
(method) Array<number>.map<number>(callbackfn: (value: number, index: number, array: number[]) => number, thisArg?: any): number[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param callbackfn — A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param thisArg — An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
The map method also takes a callback function as an argument. It calls a defined callback function on each element of an array and returns an array that contains the results. In our case, the output will be [6, 12, 18, 24, 30] as we are multiplying each array element with 3 and storing the returned array in <mappedValues > variable
Finally, I would like to say that these methods are really helpful which helps in writing less number of lines of code 🙂
Have a good grip on JavaScript by practicing from these Tutorials.
Read also on this blog: How TDD works.
3 Comments
M Bilal Jan · April 25, 2022 at 2:47 pm
I need to look a bit closer to collect real info
Really good and hardwork
admin · April 26, 2022 at 10:40 am
Thanks. M Bilal Jan
דירות דיסקרטיות בבת ים · July 20, 2022 at 5:13 am
Can I just say what a comfort to find somebody who truly understands what theyre talking about on the net. You certainly understand how to bring a problem to light and make it important. A lot more people really need to look at this and understand this side of the story. I cant believe youre not more popular because you definitely possess the gift.