Under the Hood
Whether you are an experienced or an amateur developer, you must have come across the map
, filter
and reduce
methods while coding in JavaScript. Whether you are Node.js or a React developer, understanding these methods is important as you will be asked many questions during interviews about them.
Getting Started
Let’s start directly with method #1.
The map method
The map method iterates over every element of the array and invokes the callback function you defined within it. It will always return an array and the output array will always be the same size as the input array.
const data = [
{ id: 1, name: 'shrey', count: 43 },
{ id: 2, name: 'parv', count: 23 },
{ id: 3, name: 'Dinesh', count: 58 },
{ id: 4, name: 'Akhil', count: 14 }
];
In the above example, the map function will iterate over every element of the data array and return the element with count > 30; else, it will return undefined.
data.map(item => if(item.count > 30) { return item })
// the output array will be like this
[
{ id: 1, name: 'shrey', count: 43 },
{ undefined },
{ id: 3, name: 'Dinesh', count: 58 },
{ undefined }
]
Note that the size of the final array will always remain the same.
The filter method
The filter method, by the virtue of its name, will filter the input array and return the filtered sub-array as an output. This method is usually required when filtering and sorting are executed.
data.filter(item => item.count > 30 );
// the output array will be same as those return by map method but size will decrease.
[
{ id: 1, name: 'shrey', count: 43 },
{ id: 3, name: 'Dinesh', count: 58 },
]
This is way better than the map method because you are using less space in the final array and dealing with less size is faster.
The reduce method
The reduce method is a bit different than filter and map, but it does take a callback and iterate over every element to return the single value instead of an array like the above 2 methods.
- The reducer method takes the element and keeps on adding the next element to it until it reaches the end.
- Helps to filter the single element from an array.
- Helps make calculations over an array to reduce the single value, for example, the total count of 4 students can be easily calculated using reduce method.
- Does not change the original array
data.reduce(item => { if(item.count > 30) { return item } })
// will return { id: 1, name: 'shrey', count: 43 }
Conclusion
In the JavaScript world, a lot of other methods for working with an array are available and are quite easy to understand. In today’s story, I have covered the most used and widely accepted methods.
Subscribe to our email newsletter to get such content once a week directly to your inbox.
Keep developing
Shrey
Youtube || iHateReading || Twitter
Top comments (0)