Filtering arrays

The third operation we are considering is .filter(), which will scan a complete array and generate a new one, but only with the elements that satisfy some condition, as given by you via a function. Following our example, we could pick only the males in the service result by writing the following:

// Source file: src/map_filter_reduce.js

const males = family.filter(x => x.sex === "M");
// an array with Huey, Dewey, Louie, and Donald records

Having these three operations makes it simple to do sequences of calls and generate results with little code. For example, could we find out the age of the eldest of the males in the family? Yes, quickly—with just a few lines of code:

// Source file: src/map_filter_reduce.js

const eldestMaleAge = family
.filter(x => x.sex === "M")
.map(x => x.age)
.reduce((acc, val) => Math.max(acc, val), 0); // 30

This style of chained operations is quite common: in this case, we first select the males, then we pick their ages, and then we reduce the array to a single value, the maximum: neat!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.171.121