DEV Community

KHALID ISMAIL
KHALID ISMAIL

Posted on

Javascript map, filter and reduce explained

Alt Text

Javascript has given us a lot of possibilities as a developer.

But sometimes we just need to make it more flexible for ourselves without writing bunch of codes, as we all know in ES6 javascript introduced a new concept on looping through an array which are Map, Filter and Reduce.

The Map, Filter, and Reduce is used to filter through an array of elements and then return new arrays from that element, so in this article, we going to talk about the three new arrays methods that are attached to the Es6 JavaScript.

1. Map

The JavaScript map method is used to loop true an array and then return new arrays, although it is similar to the for loop method.
The Map method can make your code simpler and readable in all aspect
Check out the examples.


   let incExp = [100, 200, -200, 300, -100]
   incExp.map(cur => console.log(cur)
   // returns each element in the array

Note: if the map method is taking more than one line of code you must include the return statement.

For example.


   let incExp = [100, 200, -200, 300, -100]
   let sum;
   incExp.map(cur => {
          return sum+= cur
    }
   // returns each element in the array

As you can see the map method is return a new array which there are two ways to do that, if you are to just return and element there is no need for writing the return statement in your code but in cases you will have to return index, element.

2. Filter

The JavaScript filter method is used to loop through and array of item return a new value based on conditional thereby pushing the truthy value as a new array.

Lets look at the examples below.


   let incExp = [100, 200, -200, 300, -100]
   incExp.filter(cur => console.log(cur > 1)
   // returns new arr with the element that are true

As you can see it returns an array that is greater than 1 in the element given to it.

With this you can have lots of possibilities to write a better organized and readable code.

Reduce

The reduce method may return different types of value based on the parameter, first it takes the array as input and then return current element, and total element.

Lets look at the examples below.


   let incExp = [100, 200, -200, 300, -100]
   incExp.reduce((cur, total) => {
          return cur + total
    }
  // returns new arr with the element that are true
  // or 

    let incExp = [100, 200, -200, 300, -100]
   incExp.reduce((cur, total) => {
          return (cur + total) + 2;
    }

So far we have talk about the three methods used in JavaScript to perform loops apart from other loop methods.

Conclusion

Weldon guys for following up and reading this articles
There are tons of resources out there to teach you more on the these javascript method.

have a nice weekend.

Feel free to contact me if you need any help in the future.
Kudos!!

Top comments (0)