The forEach:


Suppose we have an array, and each element is a person. There’s a line in front of you

Foreach is when you do something with them, one by one, in any order:

people.forEach(function (dude,index) {
  dude.pickUpSoap();
});Copy the code

Map:

A map is when you take a box (a new array) and tell them to drop their wallets in it one by one. You end up with a new array of people’s wallets in the same order as their wallets.

var wallets = people.map(function (dude) {
  return dude.wallet;
});Copy the code

reduce:

You take your wallet and count it one by one to see how much money is in it? Each time you check one, you add it to the previous sum. So at the end of the day you know how much money everybody has.

var totalMoney = wallets.reduce(function (countedMoney, wallet) {
  returncountedMoney + wallet.money; }, 0); // countedMoney starts receiving 0Copy the code



Add a filter:
As you go from wallet to wallet, don’t leave anything with less than $100 in it. Throw anything with more than $100 into a new box. You end up with a new array of all wallets with more than $100 in them:

var fatWallets = wallets.filter(function (wallet) {
  return wallet.money > 100;
});Copy the code



Finally, one difference between this analogy and the actual code,

Map and filter are immutable methods, that is, they only return a new array without changing the original array. The filter example is a bit different from the code, but for illustration, So you get the idea.