Skip to content

Instantly share code, notes, and snippets.

@benwells
Created May 12, 2016 13:40
Show Gist options
  • Select an option

  • Save benwells/0111163b3cccfad0804d994c70de7aa1 to your computer and use it in GitHub Desktop.

Select an option

Save benwells/0111163b3cccfad0804d994c70de7aa1 to your computer and use it in GitHub Desktop.

Revisions

  1. benwells created this gist May 12, 2016.
    13 changes: 13 additions & 0 deletions reduce-example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    var accounts = [
    { name: 'James Brown', msgCount: 123 },
    { name: 'Stevie Wonder', msgCount: 22 },
    { name: 'Sly Stone', msgCount: 16 },
    { name: 'Otis Redding', msgCount: 300 } // Otis has the most messages
    ];

    // get sum of msgCount prop across all objects in array
    var msgTotal = accounts.reduce(function(prev, cur) {
    return prev + cur.msgCount;
    }, 0);

    console.log('Total Messages:', msgTotal); // Total Messages: 461