Javascript Array reduce(process, initial)
Array.prototype.reduce = function(process, initial) { var reduction;/* w w w .j a va 2 s.c o m*/ if(initial === undefined){ reduction = this[0]; for(var i=1;i<this.length;i++){ reduction = process(reduction,this[i]) } } else{ reduction = initial; for(var i=0;i<this.length;i++){ reduction = process(reduction,this[i]) } } return reduction }
Array.prototype.reduce = function(process, initial) { var value = initial; for (var i = 0; i < this.length; i++) { if( ( i === 0 ) && ( value === undefined || value === null )) {//from w w w .j av a 2 s .co m value = this[0]; continue; } value = process( value, this[i] ); } return value; };
Array.prototype.reduce = function(process, initial) { const initVal = typeof this[0] === 'string' ? '' : 0; initial = initial || initVal; //w w w .j av a2 s .co m for (let i=0;i<this.length;i++){ initial = process(initial,this[i]) } return initial; }
Array.prototype.reduce = function(process, initial) { // how to access an array which invokes a function // they give us the actual function // we just have to set the initial to the first parm of the function // and call that function each time on the second parm which represent each elem in the array // need to be able to access elem of te array that func with 'this' var total;/*from w w w . j a v a 2 s .c o m*/ if(initial) { total = initial; } else { total = this.shift(); // had to remove the first element in order to avoid // duplicates in strings } for(var i = 0; i < this.length; i++) { total = process(total, this[i]); } return total; }