Skip to content

Instantly share code, notes, and snippets.

@lutzissler
Last active December 24, 2015 15:39
Show Gist options
  • Save lutzissler/6822599 to your computer and use it in GitHub Desktop.
Save lutzissler/6822599 to your computer and use it in GitHub Desktop.
jQuery implementation of ECMAScript 5’s reduce() method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce).
$.fn.reduce = function(fnReduce, initialValue) {
var values = this,
previousValue = initialValue;
values.each(function(index, currentValue) {
previousValue = fnReduce.call(currentValue, previousValue, currentValue, index, values);
});
return previousValue;
};
@mgol
Copy link

mgol commented Oct 4, 2013

You shouldn't attach it to $.fn as it doesn't operate on the DOM. Besides, there's no need for fnReduce.apply, for your use case call works better.

@lutzissler
Copy link
Author

Thanks for your feedback! It reduces the current matched set, which is why it’s attached to $.fn. The change to call is definitely worth the effort though, thanks for pointing this out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment