transforms an array by performing a function on every item in the array, and returns a new array.
We like working with map()
because it works on data arriving asynchronously, unlike for
loops where you can only work on synchronous data stored locally.
Here’s an array of stocks.
1let stocks = [
2 { symbol: "APL", price: 693 },
3 { symbol: "HUBC", price: 103 },
4 { symbol: "POL", price: 413 }
5]
We want to get a new array with only the stock symbols. Here’s how we do it with .map()
1function getStockSymbols(stocks) {
2 return stocks.map(stock => stock.symbol)
3}
4
5let symbols = getStockSymbols(stocks)
6
7console.log(symbols) // [ 'APL', 'HUBC', 'POL' ]
Here’s how we’d do it traditionally with regular for
loops.
1function getStockSymbols(stocks) {
2 let symbols = [],
3 counter,
4 stock
5
6 // Regular for loop
7 for (counter = 0; counter < stocks.length; counter++) {
8 stock = stocks[counter]
9 symbols.push(stock.symbol)
10 }
11
12 return symbols
13}
14
15let symbols = getStockSymbols(stocks)
16
17console.log(symbols) // [ 'APL', 'HUBC', 'POL' ]
And here’s how you’d do it with a forEach
loop
1function getStockSymbols(stocks) {
2 let symbols = []
3
4 // forEach loop
5 stocks.forEach(stock => symbols.push(stock.symbol))
6
7 return symbols
8}
9
10let symbols = getStockSymbols(stocks)
11
12console.log(symbols) // [ 'APL', 'HUBC', 'POL' ]
As you can see, map
is superior to both for
and forEach
.. it’s a higher-order function (word-play intended).