I will cover common Set operations 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
Here are the methods covered.
|LINQ Methods||Lodash Equivalents||Go to example|
For production codes, use Lodash as their implementation is thoroughly battle-tested.
The sample collections used in this part are shown as below.
Orders is same as last 3 series and I added
InternationalOrders for examples this time)
📝NOTE: “Union” in Lodash is named _.union.
“Intersect” compares two sequences and return another sequence with a “common” value.
How do you check for the “commonness”?
Intersect in LINQ provides an overload that lets you specify how to compare each value in two sequences by passing an object of type implementing IEqualityComparer<T> interface.
order array contains objects with a property called
id so I passed a callback (
idSelector) to let
Array.prototype.intersect to use it to make a comparison for each value in two sequences.
🔸 Except (Difference)
“Except” compares two sequences and return a new sequence with values that exists in the caller but not in the compared.
The implementation of
Array.prototype.except is almost same as intersect.
The only difference between
Array.prototype.except is whether to include the record in the other set or not.
Take a close look at callback in
🔴 Closing Remark
“Union”, “Intersect”, and “Except” are the most common Set operations.
Any feedback or error reports are always welcome.
The full source code and instructions on how to run them are on GitHub.