1. Functional programming

Let have an overview of functional programming. As we knew, this concept of programming style has become very popular in those years. The main concept of it is: the output of the method only depends on the input. Unlike the other programming style, the output may be different based on the executing time.

Functional programming depends so much on the list (array), we handle and use it almost the time when coding. the one that handles the list better may be considered as the better functional programmer.

And yes, map, filter, reduce is very powerful to handle a list/array but have no effect on the original one

2. Map, Filter, Reduce

Let focus on `map` first!

2.1 Map

So exactly what map do? Sometimes we need to access/change the value of every element of an object/array, that time we should use the map method (just forget for and forEach).

const arrayNum = [1,2,3,4];

const arrayNumDouble = arrayNum.map((index, value, array) => {
    return value * 2 
});

console.log(arrayNum); // [1, 2, 3, 4]
console.log(arrayNumDouble); // [2, 4, 6, 8]

Yeah, we get a new array, and every element was touched but not change the original is arrayNum. Ok, so let take a better practice example:

const arrayObjects = [
    {id: 1, name: "Harry"},
    {id: 2, name: "Duong"},
    {id: 3, name: "Mi"},
    {id: 4, name: "Na"}
];

const arraynNames = arrayObjects.map(item => {
    return item.name
});

console.log(arraynNames); // [Harry, Duong, Mi, Na]

We have the result is the array name of every object. simple but powerful, and of course, you can return what ever you want, do whatever you need with every item.

2.2 Filter

There are so many cases that you need to remove some elements from the array, some elements that not suitable, not adapt to the condition!

const arrayNum = [1,2,3,4];

const arrayNumEven = arrayNum.filter((index, value, array) => {
    return value % 2 == 0 
});

console.log(arrayNumEven); // [2, 4]

Filter and map basically are the same, the only difference is filter callback need to return a bool value, which is true or false, if return true, the element will be added to the target array.

2.3 Reduce

Last but very important is reduce, it takes an array as the input and calculates to only one value, let see the code below:

const arrayNum = [1,2,3,4];

const calNumber = arrayNum.reduce((cal, index, value, array) => {
    return cal + value;
});

console.log(calNumber); // 10

The difference here is the reduce callback takes the first input as the current calculated number. In the example above, we have just calculated the total value of elements in the array

3. Conclusion

Just two important things:

  • forget Loop (for/forEach), dont use them in those case above, map- filter – reduce is much better!
  • Don’t confused about the position of every input param in the callback!

Leave a Reply

Your email address will not be published.