Tuesday, November 21, 2017

JavaScript Array.Filter

Several times in the recent past I've had a need to grab certain objects from an array based on a value of one of their properties. In Linq in C# I'd do something like this:
filteredItems = allItems.Where(i => i.FirstName == "Mickey");

In TypeScript I don't have Linq functions so I need an alternative when I'm writing Angular. Fortunately, JavaScript includes the Array.prototype.filter function that works very similarly. When I want to do the exact same thing as above, but in JavaScript (and therefore in TypeScripe) I'd do this:
filteredItems = allItems.filter(i => i.FirstName === "Mickey");

Did I say they were similar? Because they're pretty much identical. I'm sure I'll be revisiting this post many times in the future.

No comments:

Post a Comment