• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • JavaScript: map and reduce

    Blogs20152015-07-14


    JavaScript: map and reduce

    Inspired by server-side MapReduce, I find js map and reduce are very powerful for accumulating purpose processing. According to MDN:

    1. The map() method creates a new array with the results of calling a provided function on every element in this array. It accepts a Array, and return a Array.
    2. The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value. It accepts a Array, and return a single value.

      arr.reduce(previousValue, currentValue[, initialValue]) If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. or if initialValue is supplied, previousValue=initialValue, otherwise is The value previously returned in the last invocation of the callback.

    By borrowing other function, such as call(), map() can accept object or string and return a filtered Array, pass to reduce(); and reduce() then continues to process to generate a array,string,object, such as dictionary set etc.

    [].map.call('12345', function(x) {
      return x;
    }).reverse().join(''); //'54321'
    
    [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
      return a.concat(b);
    }, []); //[0, 1, 2, 3, 4, 5]
    
    // more complicated:
    array.filter(function(ele) {
      //The filter() method creates a new array with all elements that pass the test implemented by the provided function.
      return ele.match(/(w+)/g);
    })
    .map(function(currentValue, index) {
      // return a new Array:
      return currentValue.value;
    })
    .reduce(function(previousValue, currentValue) {
      // accumulator 'previousValue' by loop 'currentValue'.
      return previousValue[currentValue];
    }, {})

    The following are 2 full-examples to concat of map() and reduce():

    String.prototype.map_reduce = function(){
      return this.toLowerCase().split(/W+/g)
        .reduce(function (t, w) {
          if (w) t[w] = (t[w] || 0) + 1;
          return t;
        }, {})
      }
      // usage:
      'The quick brown fox jumped over the lazy'.map_reduce()
      //will return:
      Object {the: 2, quick: 1, brown: 1, fox: 1, jumped: 1…}
    
    // from url: Javascript and MapReduce:
    var scores = Array.prototype.slice.call(document.getElementsByTagName('title'))
      .map(function(node) {
        return node.innerText.toLowerCase().match(/([a-z]+)/g);
      })
      .reduce(function(last, now) {
        now.forEach(function(word) {
          last.push(word);
        });
    
        return last;
      }, [])
      .reduce(function(last, now) {
        var index = last[0].indexOf(now);
    
        if (index === -1) {
          last[0].push(now);
          last[1].push(1);
        } else {
          last[1][index] += 1;
        }
    
        return last;
      }, [[], []])
      .reduce(function(last, now, index, context) {
        var zip = [];
        last.forEach(function(word, i) {
          zip.push([word, context[1][i]])
        });
        return zip;
      });