Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Javascripthas several array methods to operate on and iterate over arrays to perform specific transformations and computations. These provide convenient methods for such operations and can be chained to work together efficiently. The map(), reduce() and filter() methods are some of such array functions that perform the given operation on arrays and return the updated arrays. This article will discuss how the three methods can be implemented individually and in a single line using suitable examples.
.map() takes two arguments, a callback, along with some optional context. For each value, callback runs to return a new value in the resulting array, which is always the length of the original array itself.
The map function has several built-in functions for static and instance properties. Some significant built-in map functions are listed below:
Map.prototype.clear() to remove all the key-value pairs.
Map.prototype.size to return all the key-value pairs from the Map object.
Map.prototype.get(key) to return either the value associated with the key or undefined in case there isn’t any.
Map.prototype.set(key, value) to set values for keys in the Map object.
The list is over yet, there are tons of methods resides in the map() function.
E.g. for map(): For an array with multiple objects, each representing an individual, we need a final array containing just the id of every individual.
Input
var council = [
{ id: 2100, name: 'President Jacqueline' },
{ id: 2114, name: 'Vice-president James' },
{ id: 3016, name: 'House-captain Otis' },
{ id: 4818, name: 'Prefect Finneas' }
];
Output
[2100, 2114, 3016, 4818]
We could approach this from various methods. We can either create an empty array, and use .forEach(), .for(...of), or just a .for() to get the desired output.
Let us now have a look at these methods one by one:
Using .forEach():
var councilIds = [];
council.forEach(function (counc)
{
// pushing each ID onto the additional created array
councilIds.push(counc.id);
});
You can also try this code with Online Javascript Compiler
.reduce() runs a callback for every array element just like .map() does. The only difference is that reduce() passes the result of this accumulator from one array element to the other. Some built-in reduce() functions are: Array.prototype.reduce(), and the reduceRight() method which are used to apply functions against accumulators from 1. Left to right and 2. Right to left respectively.
The accumulator either contains the initial value or the return value from the previous call. The accumulator could be any string, integer, object, etc. It is the net result of the function. The present value of the accumulator is simply the element that is being worked against.
Accumulators must be passed when .reduce() is being called.
Consider the below picture to visualize the working of the accumulator:
Assume, we have an array of employees along with their years of work experience. We only want the total years of all employees’ work experience as the output.
Input
var employees = [
{
id: 111,
name: "Chelsea Foster",
years: 7,
},
{
id: 102,
name: "Aggie Sparling",
years: 13,
},
{
id: 123,
name: "Timmy Matthews",
years: 23,
},
{
id: 119,
name: "Emmet Foster",
years: 22,
}
];
Output
65
To get the total years of experience, we could straightforwardly use .reduce():
The starting value is set here as 0. After the callback runs for every array element, reduce returns the final value of the accumulator, which is 65 in our case.
filter() in Javascript
Now, if we just want some of the elements in the array we have, we can use .filter().
Input
var members =
[
{
id: 111,
name: "Chelsea Foster",
position: "Intern",
},
{
id: 102,
name: "Aggie Sparling",
position: "Employee",
},
{
id: 123,
name: "Timmy Matthews",
position: "Intern",
},
{
id: 66,
name: "Emmet Foster",
position: "Employee",
}
];
Now, if we want one array for the interns and one for employees:
.map(), .reduce() and .filter() are all used on arrays. In fact, map and filter return arrays too, meaning we can chain these calls very conveniently. Here’s an example:
Ans: .map() transforms every element in an array individually and creates a new array. filter() removes elements that are not required and creates a new array containing the ones needed. Finally, reduce() reduces all array elements into a single value.
Q2. What is the length of arrays made using .map() in javascript?
Ans: Since map() individually transforms all elements of an array to create a new array, the length of the new array is the same as that of the original one.
Q3. Does .filter() create new arrays of the same length as the previous one?
Ans: Filter removes the unrequired elements while creating a new array and only includes the ones necessary. Therefore, the length of the new array is usually lesser than that of the original one.
In this article, we learned about the map(), reduce(), and filter() methods and how we can combine them to make the code concise and efficient. We also used examples to get a better understanding of situations where such array methods could be used.
To clarify the concepts, implement the stated methods on your own and analyze the outputs.
You can go to Coding Ninjas Studio to try and solve more problems for practice. Share this blog with your friends if you found it helpful! Until then, All the best for your future endeavours, and Keep Coding.