Skip to content

Instantly share code, notes, and snippets.

@apolopena
Last active January 13, 2019 23:34
Show Gist options
  • Save apolopena/33bf55a782f0e94b57bf033298257dd3 to your computer and use it in GitHub Desktop.
Save apolopena/33bf55a782f0e94b57bf033298257dd3 to your computer and use it in GitHub Desktop.
JavaScript: Simple Reduce Examples
var miles = [{ distance: 34 }, { distance: 12 } , { distance: 1 }];
var totalDistance = miles.reduce(function(prev, item){return prev + item.distance;}, 0);
//return the total of sitting and standing chairs
var desks = [
{ type: 'sitting' },
{ type: 'standing' },
{ type: 'sitting' },
{ type: 'sitting' },
{ type: 'standing' }
];
var deskTypes = desks.reduce(function(prev, desk) {
if (desk.type === 'sitting') prev.sitting++;
if (desk.type === 'standing') prev.standing++;
return prev;
}, { sitting: 0, standing: 0 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment