Arrays + functions: map()

Map is used to loop over an existing array and returns a new array, with the result of running a function for each item of the array.

Suppose we have an array named a:

const a = [1, 2, 3]

We create another array named b, which is completely new, calling the map() method of the array a, using this syntax:

const b = a.map(() => {})

If you check what b contains, you’ll see it has 3 items in it, all with the value undefined.

Why undefined? Because we didn’t return anything from the function we passed to map().

If you returned the number 5 from that function, you’d have in b an array with 3 times the number 5:

const b = a.map(() => 5)

Things start to be useful when you realize the callback function (the function we pass to map()) receives each item’s value, and you can do many things now.

To start with, you can return the item, so you basically clone the original array, provided it’s filled with primitive values:

const b = a.map(item => item)

Now b is a copy of a.

You can choose to have in b the result of multiplying each item in a by 10:

const b = a.map(item => item * 10)

You don’t just get the item in the function, you also get its index, and the original array too:

const b = a.map((item, index, arr) => console.log(item, index, arr))

Lessons in this unit:

0: Introduction
1: ▶︎ map()
2: filter()
3: reduce()
4: sort()
5: find() and findIndex()
6: forEach()