JavaScript array methods— map, forEach, filter, reduce
Arrays:
Basically an array is a special variable which can hold multiple values. But JavaScript’s arrays are little bit different than most of the other programming languages where, it can store different datatypes within a single array. They are type independant.
let array = [ true, “JavaScript”, 100, undefined, null, { name: “John” } ]
The above array is completely fine and it doesn’t throw an error.
Most commonly used array methods:
1. map():
Basically map is not meant to be used like a loop. It is used to transform an array into another. Most of the new developers tend to use map like a loop.
The map() calls a callback function for each of the elements in the array and the return value from the callback is pushed into an array and it is returned at the end of the map().
Let’s see an example,
In the above code, each player object is passed to the callback function and each function call returns a new object of the player along with the additional field major (true/ false). The returned objects gets added to an array and at last it is assigned to playersTransformedData.
2. forEach():
The function forEach() is similar to the map(), but the difference is it does not return an array. forEach() function is basically used to iterate through each element of an array and not for transformation.
Similar to map(), forEach() also passes each element of the array to a callback function. It is mostly used to iterate and print some relevant data.
Get saravana kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s see an example,
3. filter():
As the name suggests, Array.filter() method is used to get a filtered array out of the current available array. By default, the filter method passes each element of the array to the callback function one by one.
If the callback function returns true or a value equivalent to true, the corresponding array element is appended to the filteredArray.
If the callback function returns false or a value equivalent to false, the value is ignored.
Let’s see an example,
The filteredArray contains only the players who are above 18 years old.
4. reduce():
Array.reduce() is a predefined javascript function which is completely different from the functions which we have seen son far.
As the name suggests it is used to reduce an array of values into a single value.
It passes a default parameter whose value is the return value of previous elements function call. Initially it is set to 0 or whatever value is given as a second parameter to the reduce function.
Let’s see an example,
In the above reduce function, initially count is assinged values 0 by passing it as a second argument.
For the function calls with further array elements, the count from previous function call is passed.
And atlast the final value of count after iterating through all the elements is assigned to noOfMajorPlayers variable which is 3.







