Main difference between map and reduce

后端 未结 6 1191
日久生厌
日久生厌 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:06

    Generally "map" means converting a series of inputs to an equal length series of outputs while "reduce" means converting a series of inputs into a smaller number of outputs.

    What people mean by "map-reduce" is usually construed to mean "transform, possibly in parallel, combine serially".

    When you "map", you're writing a function that transforms x with f(x) into some new value x1. When you "reduce" you're writing some function g(y) that takes array y and emits array y1. They work on different types of data and produce different results.

    0 讨论(0)
  • 2020-12-12 13:08

    Let's take a look of these two one by one.

    Map

    Map takes a callback and run it against every element on the array but what's makes it unique is it generate a new array based on your existing array.

    var arr = [1, 2, 3];
    
    var mapped = arr.map(function(elem) {
        return elem * 10;
    })
    
    console.log(mapped); // it genrate new array

    Reduce

    Reduce method of the array object is used to reduce the array to one single value.

    var arr = [1, 2, 3];
    
    var sum = arr.reduce(function(sum, elem){
        return sum + elem;
    })
    
    console.log(sum) // reduce the array to one single value

    0 讨论(0)
  • 2020-12-12 13:13

    Source

    Both map and reduce have as input the array and a function you define. They are in some way complementary: map cannot return one single element for an array of multiple elements, while reduce will always return the accumulator you eventually changed.

    map

    Using map you iterate the elements, and for each element you return an element you want.

    For example, if you have an array of numbers and want to get their squares, you can do this:

    // A function which calculates the square
    const square = x => x * x
    
    // Use `map` to get the square of each number
    console.log([1, 2, 3, 4, 5].map(square))

    reduce

    Using an array as an input, you can get one single element (let's say an Object, or a Number, or another Array) based on the callback function (the first argument) which gets the accumulator and current_element parameters:

    const numbers = [1, 2, 3, 4, 5]
    
    // Calculate the sum
    console.log(numbers.reduce(function (acc, current) {
      return acc + current
    }, 0)) // < Start with 0
    
    // Calculate the product
    console.log(numbers.reduce(function (acc, current) {
      return acc * current
    }, 1)) // < Start with 1


    Which one should you choose when you can do the same thing with both? Try to imagine how the code looks. For the example provided, you can compute the squares array like you mentioned, using reduce:

    // Using reduce
    [1, 2, 3, 4, 5].reduce(function (acc, current) {
        acc.push(current*current);
        return acc;
     }, [])
    
     // Using map
     [1, 2, 3, 4, 5].map(x => x * x)
    

    Now, looking at these, obviously the second implementation looks better and it's shorter. Usually you'd choose the cleaner solution, which in this case is map. Of course, you can do it with reduce, but in a nutshell, think which would be shorter and eventually that would be better.

    0 讨论(0)
  • 2020-12-12 13:13

    The map() function returns a new array through passing a function over each element in the input array.

    This is different to reduce() which takes an array and a function in the same way, but the function takes 2 inputs - an accumulator and a current value.

    So reduce() could be used like map() if you always .concat onto the accumulator the next output from a function. However it is more commonly used to reduce the dimensions of an array so either taking a one dimensional and returning a single value or flattening a two dimensional array etc.

    0 讨论(0)
  • 2020-12-12 13:15

    I think this picture will answer you about the difference between those HOC

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题