Skip to content

Instantly share code, notes, and snippets.

@jacomyal
Created May 17, 2013 13:54
Show Gist options
  • Save jacomyal/5599164 to your computer and use it in GitHub Desktop.
Save jacomyal/5599164 to your computer and use it in GitHub Desktop.
When and how I mostly use Array.prototype.reduce.
/**
* Here are the kind of cases I like to use Array.prototype.reduce to deal
* with:
*/
/**
* We have an array of users sorted by name. The "reduce" method can be really
* useful here:
*/
var users = [
{
id: 'wbruc',
name: 'Bruce Wayne'
},
{
id: 'djohn',
name: 'John Doe'
},
{
id: 'wjohn',
name: 'John Wayne'
}
];
/**
* 1. Indexing the array by id:
*/
var usersIndex = users.reduce(function(object, user) {
object[user.id] = user;
return object;
}, {});
/**
* 2. Finding a specific object in the array (one-line):
*/
var batman = users.reduce(function(result, user) {
return result || user.id === 'wbruc' ? user : result;
}, null);
/**
* In this use-case, I search in the whole array without breaking, when using
* Array.prototype.some could avoid that. But since "some" casts the finally
* returned value to a boolean, I cannot use it as a one-liner.
*
* So obviously, I use this last case only when my array is short and the
* operation is not repeated too often.
*
* I often transform "some" to "reduce" because I need a one-liner. And in that
* case, forgetting the "null" initial value is really bad...
*
* P.S.: And of course I would definitely enjoy Array.prototype.some to return
* the final falsy or truthy value returned by the last evalutation of the
* callback.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment