How to Implement LINQ methods in JavaScript - Part 5

blogentry, programming, quicktip, series


Photo by Jonas Vincent on Unsplash

I will cover common number aggregate methods in this article.

Here are the methods covered so far.

  1. Part 1 〰️ Select, Aggregate, Where, OrderBy (Ascending, Descending)
  2. Part 2 〰️ Any, Distinct, Concat, SelectMany
  3. Part 3 〰️ Reverse, Zip, Min/Max
  4. Part 4 〰️ Union, Intersect, Except
  5. Part 5 〰️ Sum, Average, Count
  6. Part 6 〰️ First, Last, DefaultIfEmpty, Skip, Take
  7. Part 7 〰️ Empty, Repeat, Range
  8. Part 8 〰️ All, Contains, SequenceEqual

I've covered "min" and "max" in part 3 so I won't cover them again here.

🔴 Overview

In this article, I will cover following methods.

[table id=5 /]

And I will try to stick to using VanillaJS as I have so far.

The sample collections used in this article.





🔴 Examples

🔸 Sum

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.

🔸 Average

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.

🔸 Count

Count is overloaded in LINQ; One that simply returns a number of element in a sequence, and the other that accepts a predicate which lets you test each item.

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 array.length but filter is required for testing each element in an array.

🔴 Closing Remark

Sum, Average, and Count are often used and easy to implement (using for/each loops). I used reduce and filter to implement to make it look as similar to LINQ methods.

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.