Main difference between map and reduce

后端 未结 6 1194
日久生厌
日久生厌 2020-12-12 12:38

I used both methods but I am quite confused regarding the usage of both methods.

Is anything that map can do but reduce can not and vice ve

6条回答
  •  攒了一身酷
    2020-12-12 13:17

    To understand the difference between map, filter and reduce, remember this:

    1. All three methods are applied on array so anytime you want to make any operation on an array, you will be using these methods.
    2. All three follow functional approaches and therefore the original array remains the same. Original array doesn't change instead a new array/value is returned.
    3. Map returns a new array with the equal no. of elements as there are in the original array. Therefore, if the original array has 5 elements, the returned array will also have 5 elements. This method is used whenever we want to make some change on every individual element of an array. You can remember that every element of ann array is being mapped to some new value in output array, therefore the name map For eg,

    var originalArr = [1,2,3,4]
    //[1,2,3,4]
    var squaredArr = originalArr.map(function(elem){
      return Math.pow(elem,2);
    });
    //[1,4,9,16]

    1. Filter returns a new array with equal/less number of elements than the original array. It returns those elements in the array which have passed some condition. This method is used when we want to apply a filter on the original array therefore the name filter. For eg,

    var originalArr = [1,2,3,4]
    //[1,2,3,4]
    var evenArr = originalArr.filter(function(elem){
      return elem%2==0;
    })
    //[2,4]

    1. Reduce returns a single value, unlike a map/filter. Therefore, whenever we want to run an operation on all elements of an array but want a single output using all elements, we use reduce. You can remember an array's output is reduced to a single value therefore the name reduce. For eg,

    var originalArr = [1,2,3,4]
    //[1,2,3,4]
    var sum = originalArr.reduce(function(total,elem){
      return total+elem;
    },0)
    //10

提交回复
热议问题