I will cover common number aggregate methods in this article.
Here are the methods covered so far.
- Part 1 〰️ Select, Aggregate, Where, OrderBy (Ascending, Descending)
- Part 2 〰️ Any, Distinct, Concat, SelectMany
- Part 3 〰️ Reverse, Zip, Min/Max
- Part 4 〰️ Union, Intersect, Except
- Part 5 〰️ Sum, Average, Count
- Part 6 〰️ First, Last, DefaultIfEmpty, Skip, Take
- Part 7 〰️ Empty, Repeat, Range
I’ve covered “min” and “max” in part 3 so I won’t cover them again here.
In this article, I will cover following methods.
And I will try to stick to using VanillaJS as I have so far.
The sample collections used in this article.
I will show you “Sum” demo first since “Average” is basically a sum divided by count.
Array.prototype.sum simply reduces each order quantity by summing it in the callback.
Note 📝: It’s exactly the same as the reduceDemo.
Now let’s get an average quantity ordered.
The only difference here is that sum is divided by the order count to calculate an average.
I will implement the one with the predicate as the former is too simple.
The demo counts number of orders placed on and after March of 2018.
Count without a predicate is same as
filter is required for testing each element in an array.
🔴 Closing Remark
As always, I’ve not tested edge cases for Array prototypes so use the code at your own risk 😃.
Please let me know should you find any errors or improvements I can make to the codes.
The full source code and instructions on how to run them are on GitHub.