Skip to content

Commit

Permalink
sum values in array of objects
Browse files Browse the repository at this point in the history
  • Loading branch information
matt-sm committed Aug 7, 2018
1 parent e4f27f2 commit 725e1d1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
8 changes: 7 additions & 1 deletion javascript/reduce.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
module.exports.sum = (arr) => {
module.exports.sum = arr => {
return arr.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 0)
}

module.exports.sumObj = arr => {
return arr.reduce((accumulator, currentValue) => {
return accumulator + Object.values(currentValue)[0]
}, 0)
}
5 changes: 5 additions & 0 deletions javascript/reduce.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,9 @@ const reduce = require('./reduce')
test('sum array values', () => {
expect(reduce.sum([1,2,3])).toBe(6)
expect(reduce.sum([])).toBe(0)
})

test('sum object array', () => {
expect(reduce.sumObj([{x:1}, {y:2}, {z:3}])).toBe(6)
expect(reduce.sumObj([])).toBe(0)
})

0 comments on commit 725e1d1

Please sign in to comment.