zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Chaining the Array map and filter methods

JavaScriptMap The and Array filter methods
2023-09-14 08:59:21 时间

Both map and filter do not modify the array. Instead they return a new array of the results. Because both map and filter return Arrays, we can chain these functions together to build complex array transformations with very little code. Finally we can consume the newly created array using forEach. In this lesson, we will learn how to build nontrivial programs without using any loops at all.

 

var stocks = [
  { symbol: "XFX", price: 240.22, volume: 23432 },
  { symbol: "TNZ", price: 332.19, volume: 234 },
  { symbol: "JXJ", price: 120.22, volume: 5323 },
];

var filteredStockSymbols = 
  stocks.
    filter(function(stock) {
      return stock.price >= 150.00;
    }).
    map(function(stock) {
      return stock.symbol;
    })

filteredStockSymbols.forEach(function(symbol) {
  console.log(symbol);
})