|
| 1 | +# 0013 ageSumObject ( L-B ) |
| 2 | + |
| 3 | +## Problem |
| 4 | + |
| 5 | +Given an array of objects, return the sum of the age of all the objects. |
| 6 | + |
| 7 | +## Test Cases |
| 8 | + |
| 9 | +- Input: [{name: 'John', age: 20}, {name: 'Jane', age: 30}, {name: 'Jack', age: 40}], Output: 90 |
| 10 | +- Input: [{name: 'John', age: 20}, {name: 'Jane', age: 30}], Output: 50 |
| 11 | +- Input: [{name: 'John', age: 20}], Output: 20 |
| 12 | + |
| 13 | +## Solution |
| 14 | + |
| 15 | +```javascript |
| 16 | + |
| 17 | +const people = [ |
| 18 | + { name: "DevvSakib", age: 20 }, |
| 19 | + { name: "Taulo", age: 15 }, |
| 20 | + { name: "Paulo", age: 22 }, |
| 21 | + { name: "Kaulo", age: 52 }, |
| 22 | + { name: "Yaulo", age: 21 }, |
| 23 | +] |
| 24 | + |
| 25 | +const sumAge = people.reduce((ac, cur) => ac + cur.age, 0) |
| 26 | +``` |
| 27 | + |
| 28 | +## How it works |
| 29 | + |
| 30 | +- We use the reduce method to iterate through the array and add the age of each object to the accumulator. |
| 31 | +- The reduce method takes two parameters, the first is a callback function and the second is the initial value of the accumulator. |
| 32 | +- The initial value of the accumulator is 0. |
| 33 | +- The reduce method returns the final value of the accumulator. |
| 34 | +- The final value of the accumulator is the sum of the age of all the objects. |
| 35 | + |
| 36 | +## References |
| 37 | + |
| 38 | +- [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) |
| 39 | +- [Wikipedia](https://en.wikipedia.org/wiki/Reduce_(higher-order_function)) |
| 40 | +- [GeeksforGeeks](https://www.geeksforgeeks.org/javascript-array-reduce-method/) |
| 41 | +- [JavaScript Info](https://javascript.info/array-methods#reduce-reduceright) |
| 42 | + |
| 43 | +## Problem Added By |
| 44 | + |
| 45 | +- [GitHub](https://www.github.com/devvsakib) |
| 46 | +- [LinkedIn](https://www.linkedin.com/in/devvsakib) |
| 47 | +- [Twitter](https://twitter.com/devvsakib) |
| 48 | + |
| 49 | +## Contributing |
| 50 | + |
| 51 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
| 52 | + |
| 53 | +Please make sure to update tests as appropriate. |
0 commit comments