Advertisement
Guest User

Untitled

a guest
Apr 1st, 2015
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. /* accept an array of stocks, pull out the symbol from each one of
  2. those stocks, put the symbols in an array and return it */
  3. /*
  4. This process of applying some transformation to every item in an
  5. array, and creating an array to hold all of the results is very common.
  6. The Array has a map method which is used to make this even shorter.
  7. */
  8. function getStockSymbols(stocks) {
  9. // var symbols = [];
  10.  
  11. // /* forEach is really convenient if you want to do something
  12. // to every item in an array.
  13. // */
  14. // stocks.forEach(function(stock) {
  15. // symbols.push(stock.symbol);
  16. // });
  17.  
  18.  
  19. // // for(counter = 0; counter < stocks.length; counter++) {
  20. // // stock = stocks[counter];
  21. // // symbols.push(stock.symbol);
  22. // // }
  23.  
  24. // return symbols;
  25.  
  26.  
  27. return stocks.map(function(stock) {
  28. return stock.symbol;
  29. });
  30. }
  31.  
  32. // /* The whole job of the projection function is to transform the item in the array to something else
  33. // */
  34. // Array.prototype.map = function (projection) {
  35. // var results = [];
  36.  
  37. // /*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. */
  38. // this.forEach( function(item) {
  39. // results.push(projection(item));
  40. // });
  41.  
  42. // return results;
  43. // };
  44.  
  45. var symbols = getStockSymbols([
  46. {symbol: "YHOO", price: 44.78, volume: 22000},
  47. {symbol: "AAPL", price: 102.68, volume: 25000},
  48. {symbol: "GOOG", price: 500.21, volume: 20000},
  49. ]);
  50.  
  51. console.log(JSON.stringify(symbols));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement