Please I need to understand map and reduce properly

I just know map and reduce are functions. And reduce is a powerful tool.
unfortunately I don’t get the concept.
Please your explanation should be as simple as possible. Thanks

Right, they are very important and powerful. They are also very confusing if you are starting out.

map is probably the easiest to understand. It takes in an array and returns a new array. If you have an array and want a new array where each element is based on the corresponding element of the original array, then map is probably what you want.

const arr = [1, 2, 3];
const squares = => el * el)
// [1, 4, 9]

reduce is a little weirder. Don’t feel bad - last year I had to explain how reduce works to a senior dev. It takes in an array and “reduces” it to a single value.

const arr = [1, 2, 3];
const total = arr.reduce((sum, el) => sum + el, 0)
// 6

Here, we are summing the numbers. It starts at 0 (the second parameter) and then it goes through and adds the number to the “sum”, the running total (which started out at 0).

Another example, counting how many odd numbers there are:

const arr = [1, 3, 4, 17];
const numOdd = arr.reduce((sum, el) => el % 2 === 1 ? sum + 1 : sum, 0)
// 3

If the number is odd, it returns the sum + 1. If not, it just returns the sum unchanged.

Yeah, it’s weird at first. But it’s also very powerful. You can actually use it to duplicate all the other prototype methods.

I would study these. Maybe look up some youtube videos on them. And then, if you want to really understand them, write your own versions.

MDN is a great resource to read about array methods.

1 Like

map is simple indeed. reduce is complicated but i hope to conquer it with practice. Thanks for the insight.

Okay thank you so much