

Understanding Map, Filter & Reduce functions.
source link: https://dev.to/klc/understanding-map-filter-reduce-functions-22b
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.


Understanding Map, Filter & Reduce functions.
If you still don't feel comfortable with these functions or simply need a refresher, well you are at the right place :)
Before we jump in, I'd like to talk about what these functions have in common. Can you take a guess? They are both referred to as Higher-Order Functions.
What's a higher-order function?
A higher-order function (HOF) is a function that can take another function as an argument or that can return a function as its result. All other functions are simply First-Order Functions.
Why use a HOF? 🤔
It allows us to keep our code DRY and more flexible. (Let me know if you are interested to know HOF more in-depth :-)
Alright, now that we have some background let's start, shall we?
.Map()
The map() method performs a callback function on each element in an array. It will return a new array from the returned values so that the initial array can stay unmodified.
Let's take a look :)
const test = [1,3,-4,5,9,2]
const newTest = test.map(function (x) {
return x*x;
});
console.log(newTest);
// output: [1,9,16,25,81,4]
So what we did here was, multiply each number by itself inside the test array
then return the value inside a new array.
Alright, now I'm sure we can write this function on a single line to make it a little bit cleaner :)
Cleaner code 👇
const test = [1,3,-4,5,9,2]
const newTest = test.map((x) => x*x);
console.log(newTest);
// Output: [1,9,16,25,81,4]
.Filter()
As the name suggests 'filter', it will allow you to filter a range of data based on the given conditions.
Similarly to the map function, the .filter() will also perform a callback function on each element in an array. Then, using a true or false condition, it will return a new array filled with elements that are true to that condition.
For example:
const score = [1,2,9,6,3,-8]
const newScore = score.filter(function (x) {
return x%2 === 0;
});
console.log(newScore);
// Output: [2,6,-8]
In this example, we wanted to filter out all the odd numbers and then return only even numbers.
Is 1 true
to the condition? No, so don't return it.
Is 2 true
to the condition? Yes, then return it.
And so on...
This function can also be written on a single line. Can you give it a shot? :)
.Reduce()
The .reduce() method iterates through an array and returns a single value.
It takes a callback function with two parameters (accumulator, currentValue) as arguments. The accumulator
is the value returned from the previous iteration and the currentValue
is the current element being processed in the array.
Let's take an example.
const numbers = [1,3,7,4,5]
const totalNumbers = numbers.reduce(function (acc, currVal) {
return acc + currVal;
}, 0); //initializing the accumulator to 0
console.log(totalNumbers);
// Output: [20]
So here, we summed all elements of the array and then returned a single value (where the output is 20). In other words, reducing the array to a single value.
Great! Now that we've learned these functions, let's take a quick look at the summary :-)
Summary
.Map()
- Performs a callback function on each element in an array.
- Creates a new array from the callback function.
- Does not change the original array.
- Does not execute the function for empty elements.
.Filter()
- Performs a callback function on each element in an array.
- Creates a new array filled with elements that passed the true/false condition based on the given instructions.
- Does not change the original array.
.Reduce()
- Returns a single value (using the accumulator).
- Executes a reducer function for an array element.
- Does not change the original array.
Before we wrap this up, feel free to check in the comment for some additional information written by some awesome users from this community :) You can add some details too if you think I might've missed something ;)
Hope you enjoyed this article ❤️
That's it! This was a quick refresher for the map, filter & reduce functions.
Feel free to bookmark this if you'd like to come back at it in the future.
Let me know if you enjoyed it by leaving a like or a comment :) or if there is a topic that you'd like me to write about.
Thanks for your time,
Happy coding :)
Recommend
-
165
Map, Filter and ReduceOriginally published by Alexander Kondov on September 14th 2017 7,489 reads5
-
33
A while back I written anarticle about some interesting array's functionalities - with .map() , .reduce() and .filter() being only a small fraction of them. But, because of the numb...
-
12
March 20, 2015 JavaScript’s Map, Reduce, and Filter As engineers we build and manipulate arrays holding numbers, strings, booleans and objects al...
-
13
Tutorial How To Use map(), filter(), and reduce() in JavaScript Development
-
5
map、reduce 和 filter 是三个非常实用的 JavaScript 数组方法,赋予了开发者四两拨千斤的能力。我们直接进入正题,看看如何使用(并记住)这些超级好用的方法! Array.map()Array.map() 根据传递的转换函数,更新给定数组中的每...
-
5
Bash版的join,map和filter 今天看到有人用Bash实现了join,map和filer函数(可惜没有reduce函数),觉得很有趣,所以记录下来 join 函数 join() { { local indelimiter; indelimiter="${1- }" ; local outdelimiter;...
-
7
Arrays are one of the most popular data types used in javascript as they have variety of methods that makes it easy to use. In this article, I will be talking about three popular array methods; the filter() method, the
-
15
Function Decorator, Map/Filter/Reduce in Python 发表于 2021-10-25...
-
8
Map, Filter e Reduce em JavaScript O que são map, filter e reduce? São funções no protótipo de um array JavaScript e podem ser usadas para operações baseadas em iterações em uma coleção de itens armazenados nesse arra...
-
9
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK