Main difference between map and reduce

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

提交回复
热议问题