DEV Community

Cover image for map(), filter() & reduce() in javascript👩‍💻
Aishanii
Aishanii

Posted on • Updated on

map(), filter() & reduce() in javascript👩‍💻

These all are super important and are often used while developing a project or website. map(), filter & reduce() are higher order functions, i.e. functions which have another function inside them.

1. map()

A map function basically iterates and applies a given operation on each element.

arr=[1,2,4,3,5,6]

function checkEven(x){
    return x%2==0;
}
const ans=arr.map(checkEven)
console.log(ans)
Enter fullscreen mode Exit fullscreen mode

Image description

Here it basically returns where an element is even or not and modifies value of each element present.

2. filter()

This function takes an array and check a condition on each element and filters out false values.

arr=[1,2,4,3,5,6]

const ans=arr.filter(function checkEven(x){
    return x%2==0;
})
console.log(ans)
Enter fullscreen mode Exit fullscreen mode

Image description

Here all the false values are removed. These functions do not reflect changes in the main array, arr.

3. reduce()

boils down the output of an operation over the whole array to a single answer.

It takes an accumulator that keeps track of ans at every step and a current element. Here our ans is the accumulator and x is the current element of the array.

The },0) part, this zero is the initial value of the accumulator ans.

arr=[2,4,6,6,8,9,22]

const ans=arr.reduce(function checkMax(ans, x){
    ans=ans>x?ans:x
    return ans;
},0)

console.log(ans)
Enter fullscreen mode Exit fullscreen mode

Image description

Here we keep track of maximum element and compare it with current to update it if bigger than max.

You can even pass arrow functions inside these functions. ⭐ MDN -Arrow functions

Top comments (3)

Collapse
 
rollergui profile image
Guilherme

good post!

and just in case you didn't know, you can add the language in the code block, to add syntax highlight :) just add the language name after the opening backticks like

```javascript
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aishanipach profile image
Aishanii

That was helpful, thank you so much!

Collapse
 
amirrezaheydari profile image
amirreza heydari

Please participate in my latest project, thank you

My Project