Created
June 16, 2015 15:35
-
-
Save ajcrites/3409875bd9c62ce3379b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var data = [ | |
| [ | |
| {field: 123, sum: 100}, | |
| {field: 345, sum: 98} | |
| ],[ | |
| {field: 123, sum: 12}, | |
| {field: 345, sum: 20} | |
| ] | |
| ]; | |
| console.log( | |
| data | |
| .reduce((a, b) => a.concat(b)) | |
| .reduce((a, b) => { | |
| var idx = a.findIndex(elem => elem.field == b.field); | |
| if (~idx) { | |
| a[idx].sum += b.sum; | |
| } | |
| else { | |
| a.push(JSON.parse(JSON.stringify(b))); | |
| } | |
| return a; | |
| }, []) | |
| ); | |
| console.log( | |
| data | |
| .reduce(function (a, b) { return a.concat(b) }) | |
| .reduce(function (a, b) { | |
| var idx = -1; | |
| a.forEach(function (elem, index) { | |
| if (elem.field == b.field) { | |
| idx = index; | |
| } | |
| }); | |
| if (~idx) { | |
| a[idx].sum += b.sum; | |
| } | |
| else { | |
| a.push(JSON.parse(JSON.stringify(b))); | |
| } | |
| return a; | |
| }, []) | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment