1. 4
    Chaining the Array map and filter methods
    3m 5s

Chaining the Array map and filter methods

InstructorJafar Husain

Share this video with your friends

Send Tweet

Both map and filter do not modify the array. Instead they return a new array of the results. Because both map and filter return Arrays, we can chain these functions together to build complex array transformations with very little code. Finally we can consume the newly created array using forEach. In this lesson, we will learn how to build nontrivial programs without using any loops at all.

alfapagal
~ 9 years ago

Hi Jafar,

Great tutorial, Now I am eager to replace my loops with these functions in my code. Two questions for you : 1 ) What will be the performance ramifications of chaining Array map and filter methods when compared to a single loop or a single forEach? 2) You mentioned looping is not an option when the data is coming asynchronously. I didn't understand this point. Why will looping not be an option in such scenarios?

Ryan Huber
~ 8 years ago

When would you use forEach over .map as they both seem to do the same thing to me.

Joel Hooks
~ 8 years ago

When would you use forEach over .map as they both seem to do the same thing to me.

Hey Ryan, they seem similar for sure, but map always produces a new collection and forEach simply iterates over a collection. Map is going to be the goto preference, in general.

Ryan Huber
~ 8 years ago

Thanks Joel!

Koombea
~ 8 years ago

First that all, thas for this series. I have a question: wht do you mean by "However, loops are no good to us when we're trying to work with data that's arriving asynchronously like with events." Would you mind sharing a fiddle? Thanks in advance

Jafar Husaininstructor
~ 8 years ago

I mean that you can't wait for an event in a loop. You have to attach an event handler. Furthermore you cannot repeat an asynchronous operation in a loop, because loops run their body immediately whereas async operations are resumed in a callback.

Kate
~ 8 years ago

This is simpler:

function getStockSymbols(stocks, minPrice) { return stocks .filter((stock)=> stock.price>= minPrice) .map((stock)=>stock.symbol) }

Jonathan
~ 7 years ago

I don't necessarily agree with what Jafar says, "write complex programs, all! without ever writting a loop" .... so what do you think the function is doing??? is looping over the elements in the array and at the end of the day is blocking io!