Employ .flatMap()
and compare the current values with future values:
x < a[i+1] ? a[i+1] : []
I have noticed that there seems to be limited utility for using .flatMap()
as a filter.
Therefore, why not opt for .map()
instead of .flatMap()
? Since .flatMap()
essentially serves as an equivalent but with an additional step? This supplementary step enables me to devise a more straightforward logic where I can utilize simpler algorithms without having to concern myself with common side effects associated with handling arrays, such as obtaining empties. Here's a comparison between example #1 using .flatMap()
and another version utilizing .map()
.
const data = [158, 164, 742, 99, 155, 250, 240, 87];
let resA = data.flatMap((x, i, a) => x < a[i + 1] ? a[i + 1] : []);
console.log(resA);
let resB = data.map((x, i, a) => x < a[i + 1] ? a[i + 1] : '');
console.log(resB);
Both .map()
and .flatMap()
necessitate returning data after each iteration, yet due to .flatMap()
containing a built-in .flat()
method, it allows for returning an empty array that equates to nothing, which is superior to returning an empty string ('') or undefined
.
What about using .filter()
, which undeniably appears to be the most straightforward solution? Let's compare Vectorjohn's callback here with my callback:
i > 0 && x > a[i - 1] // Vectorjohn, employing .filter()
x < a[i + 1] ? a[i + 1] : [] // My approach, utilizing .flatMap()
When utilizing .filter()
, there is typically no need to worry about overshooting zero and triggering a return of
undefined</code, since <code>.filter()
solely returns truthy data and never falsey data. Hence, his callback might simply be the reverse of my callback by eliminating
i > 0 &&
:
x > a[i - 1] // .filter() will return x
x < a[i + 1] ? a[i + 1] : [] // .flatMap() will yield a[i + 1]
My approach doesn't automatically remove undefined, making it slightly more verbose than Vj's (once corrected). However, .flatMap()
offers far greater versatility compared to .filter()
. While .filter()
consistently returns the current value (x
) on each iteration, .flatMap()
has the ability to yield anything (a[i + 1]
), multiple items (["any", x]
), or nothing ([]
) during each iteration.
Illustrative Example 1
const data = [158, 164, 742, 99, 155, 250, 240, 87];
let res = data.flatMap((x, i, a) => x < a[i + 1] ? a[i + 1] : []);
console.log(res);