开发者

What are the advantages of Javascript's reduce() function? (and map())

I'm trying to decide whether to use the reduce() method in Javascript for a function I need to write which is something like this

var x = [some array], y = {};
for (...) {
    someOperation(x[i]);
    y[x[i]] = "some other value";
}

Now this can obviously be written as a reduce() function in the following ma开发者_如何学Pythonnner:

x.reduce(function(prev, current, index, arr) {
    someOperation(current);
    prev[current] = "some other value";
    return prev;
}, {})

Or something like that. Is there any performance or other difference between the two? Or some other reason (like browser support, for instance) due to which one should be favoured over the other in a web programming environment? Thanks.


Even though I prefer these operations (reduce, map, filter, etc.), it's still not feasible to use them because of certain browsers that do not support them in their implementations. Sure, you can "patch" it by extending the Array prototype, but that's opening a can of worms too.

I don't think there's anything inherently wrong with these functions, and I think they make for better code, but for now it's best not to use them. Once a higher percentage of the population uses a browser that supports these functions I think they'll be fair game.

As far as performance, these will probably be slower than hand written for loops because of the overhead from function calls.


map and filter and reduce and forEach and ... (more info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Iteration_methods ) are far better than normal loops because:

  1. They are more elegant
  2. They encourage functional programming (see benefits of functional programming)
  3. You will need to write functions anyway and pass into them, as parameters, iteration variables. This is because javascript has no block scope. Functions like map and reduce make your job so much easier because they automatically set up your iteration variable and pass it into your function for you.

IE9 claims to support these. They're in the official javascript/ecmascript spec. If you care about people who are using IE8, that is your prerogative. If you really care, you can hack it by overriding Array.prototype for ONLY IE8 and older, to "fix" IE8 and older.


reduce is used to return one value from an array, as a result of sequentially processing the results of the previous elements.

reduceRight does the same, but starts at the end and works backwards.

map is used to return an array whose members have all been passed through a function.

neither method affects the array itself.

var A1= ['1', '2', '3', '4', '5', '6', '7',' 8'];

// This use of map returns a new array of the original elements, converted to numbers-

A1=A1.map(Number); // >> each of A1's elements converted to a number

// This reduce totals the array elements-

var A1sum= A1.reduce(function(a, b){ return a+b;});

// A1sum>> returned value: (Number) 36

They are not supported in older browsers, so you'll need to provide a substitute for them. Not worth it if all you are doing can be replicated in a simple loop.

Figuring the standard deviation of a population is an example where both map and reduce can be effectively used-

Math.mean= function(array){
    return array.reduce(function(a, b){ return a+b; })/array.length;
}
Math.stDeviation=function(array){
    var mean= Math.mean(array);
    dev= array.map(function(itm){return (itm-mean)*(itm-mean); });
    return Math.sqrt(dev.reduce(function(a, b){ return a+b; })/array.length);
}


var A2= [6.2, 5, 4.5, 6, 6, 6.9, 6.4, 7.5];
alert ('mean: '+Math.mean(A2)+'; deviation: '+Math.stDeviation(A2))


kennebec - good going, but your stDeviation function calls reduce twice and map once when it only needs a single call to reduce (which makes it a lot faster):

Math.stDev = function (a) {
    var n = a.length;
    var v = a.reduce(function (v, x) {
      v[0] += x * x;
      v[1] += x;
      return v;
    }, [0,0]);
    return Math.sqrt( (v[0] - v[1]*v[1] / n) / n );
}

Should do a conversion to number when assigning to v[1] to make sure string numbers don't mess with the result and the divisor in the last line should probablly be (n - 1) in most cases, but that's up to the OP. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜