The Research Nest
Published in

The Research Nest

A quick revision of some important JavaScript array functions using practical examples

Reduce, Filter, Includes, Map, ForEach

Photo by Blake Connally on Unsplash
First API
Sample JSON response from Coinbase's currency API.
https://api.coinbase.com/v2/currencies
Note: This is just a sample. Actual response is much larger.
This API returns a list of currencies and their ids {
"data": [
{
"id": "AED",
"name": "United Arab Emirates Dirham",
"min_size": "0.01000000"
},
{
"id": "AFN",
"name": "Afghan Afghani",
"min_size": "0.01000000"
},
{
"id": "ALL",
"name": "Albanian Lek",
"min_size": "0.01000000"
},
{
"id": "AMD",
"name": "Armenian Dram",
"min_size": "0.01000000"
},
}
}
Second API
Sample JSON response from Coinbase's exchange rate API
https://api.coinbase.com/v2/exchange-rates?currency=BTC
{
"data": {
"currency": "BTC",
"rates": {
"AED": "36.73",
"AFN": "589.50",
"ALL": "1258.82",
"AMD": "4769.49",
"ANG": "17.88",
"AOA": "1102.76",
"ARS": "90.37",
"AUD": "12.93",
"AWG": "17.93",
"AZN": "10.48",
"BAM": "17.38",
}
}
}

Using Filter and Includes

These currencies could be configured elsewhere.requiredCurrencies = ['US Dollar', 'Indian Rupee', 'Japanese Yen']
Here, we assume data is the array of JSONs we get in the API response object.filteredData = data.filter((item) => requiredCurrencies.includes(item.name))// Filtered data output
[
{
"id": "INR",
"name": "Indian Rupee",
"min_size": "0.01000000"
},
{
"id": "JPY",
"name": "Japanese Yen",
"min_size": "1.00000000"
},
{
"id": "USD",
"name": "US Dollar",
"min_size": "0.01000000"
}
]
filteredData2 = data.filter((item) => 
{
console.log('test');
return requiredCurrencies.includes(item.name)
});

Using Map and ForEach

LabeledData = currencies.map((item) => {
return {
label: item['name'],
value: rates[item.id]
}
});
[
{
"label": "United Arab Emirates Dirham",
"value": "3.673"
},
{
"label": "Afghan Afghani",
"value": "88.499983"
},
{
"label": "Albanian Lek",
"value": "111.05"
},
{
"label": "Armenian Dram",
"value": "488.092713"
},
{
"label": "Netherlands Antillean Gulden",
"value": "1.80142"
},
{
"label": "Angolan Kwanza",
"value": "450.646"
},
{
"label": "Argentine Peso",
"value": "110.698001"
},
]

Using Reduce

portfolio = [
{
"label": "BTC",
"quantity": 3,
"rate": 200,
},
{
"label": "ETH",
"quantity": 5,
"rate": 100,
},
{
"label": "LUNA",
"quantity": 2,
"rate": 50,
},
{
"label": "SOL",
"quantity": 10,
"rate": 10,
},
]
netWorth = sum(quantity * rate)
netWorth = 3*200 + 5*100 + 2*50 + 10*10 = $ 1300
initial = 0; //Declare an initial valuenetWorth = portfolio.reduce((netValue, item) => netValue + item.quantity*item.rate, initial);// This computes to networth = 1300

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
XQ

Tech 👨‍💻 | Life 🌱 | Careers 👔 | Poetry 🖊️