You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
875 B

4 years ago
  1. # `sum()`
  2. The sum method returns the sum of all items in the collection:
  3. ```js
  4. collect([1, 2, 3]).sum();
  5. // 6
  6. ```
  7. If the collection contains nested arrays or objects, you should pass a key to use for determining which values to sum:
  8. ```js
  9. const collection = collect([
  10. { name: 'My story', pages: 176 },
  11. { name: 'Fantastic Beasts and Where to Find Them', pages: 1096 },
  12. ]);
  13. collection.sum('pages');
  14. // 1272
  15. ```
  16. In addition, you may pass your own callback to determine which values of the collection to sum:
  17. ```js
  18. const collection = collect([
  19. { name: 'Desk', colors: ['Black', 'Mahogany'] },
  20. { name: 'Chair', colors: ['Black'] },
  21. { name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
  22. ]);
  23. const total = collection.sum(product => product.colors.length);
  24. // 6
  25. ```
  26. [View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/sum.js)