Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* accept an array of stocks, pull out the symbol from each one of
- those stocks, put the symbols in an array and return it */
- /*
- This process of applying some transformation to every item in an
- array, and creating an array to hold all of the results is very common.
- The Array has a map method which is used to make this even shorter.
- */
- function getStockSymbols(stocks) {
- // var symbols = [];
- // /* forEach is really convenient if you want to do something
- // to every item in an array.
- // */
- // stocks.forEach(function(stock) {
- // symbols.push(stock.symbol);
- // });
- // // for(counter = 0; counter < stocks.length; counter++) {
- // // stock = stocks[counter];
- // // symbols.push(stock.symbol);
- // // }
- // return symbols;
- return stocks.map(function(stock) {
- return stock.symbol;
- });
- }
- // /* The whole job of the projection function is to transform the item in the array to something else
- // */
- // Array.prototype.map = function (projection) {
- // var results = [];
- // /*The reason we use this.forEach is that the map method is actually being added to the array itself. so this in the context of this funciton is an array. */
- // this.forEach( function(item) {
- // results.push(projection(item));
- // });
- // return results;
- // };
- var symbols = getStockSymbols([
- {symbol: "YHOO", price: 44.78, volume: 22000},
- {symbol: "AAPL", price: 102.68, volume: 25000},
- {symbol: "GOOG", price: 500.21, volume: 20000},
- ]);
- console.log(JSON.stringify(symbols));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement