Examples of FOREACH array method usage in javascript

  • 2021-01-18 06:16:29
  • OfStack

The Array.prototype.forEach () method causes each item in the array to execute the given function once. - MDN

Let's say you have a scenario where you get an array like this

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

You need to create a new array for symbol in it, i.e

[ "XFX", "TNZ", "JXJ"]
1. for loop can be used to achieve:


function getStockSymbols(stocks) {
 var symbols = [],
   stock,
   i;
   
 for (i = 0; i < stocks.length; i++) {
  stock = stocks[i];
  symbols.push(stock.symbol);
 }

 return symbols;
}

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

Output: "[/"XFX/", "TNZ/", "JXJ/"]" "

You can also use the ES35en method of ES34en to simplify the code, and the output is exactly the same.


function getStockSymbols(stocks) {
 var symbols = [];

 stocks.forEach(function(stock) {
  symbols.push(stock.symbol);
 });

 return symbols;
}


Related articles: