DEV Community

Aditya Vivek Thota
Aditya Vivek Thota

Posted on • Originally published at Medium on

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

Reduce, Filter, Includes, Map, ForEach

One of the fundamental things we do in frontend development is to fetch the data from an API, do some operations or check for something in it and then display it on the UI.

This data is generally read as a JSON or an array of JSON. Some of the most common operations we try to perform on this data are as follows:

  • Extracting values meeting certain conditions using the Filter function.
  • Computing a value across an array using the Reduce function.
  • Modifying, creating, or comparing objects/values by iterating over the array using Map or ForEach.
  • Perform some operations with data to get some required results that are to be displayed on the UI.

Let’s take an example to quickly understand how to properly use these Javascript functions. Let’s say we are trying to build some UI dashboard showing cryptocurrency data that we get from Coinbase’s public APIs. Below is the kind of real data you might actually deal with in many different use cases.

**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"
    },
  }
}
Enter fullscreen mode Exit fullscreen mode

Here’s another API that gives the exchange rate for the corresponding currency code with Bitcoin.

**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",
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

What kind of things we might need to do with this data?

Using Filter and Includes

Filter can be used whenever you want to check if some condition is satisfied for each item in the array and if yes, put them in a new array.

In our example, we want to get the currency code objects of a list of predetermined currencies from the entire list and you want to use those currency codes alone to render something.

// These currencies could be configured elsewhere.

requiredCurrencies = ['US Dollar', 'Indian Rupee', 'Japanese Yen']
Enter fullscreen mode Exit fullscreen mode

Now, we would want to filter the currency codes from the big JSON list (first API) where the currency belongs to our required list.

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"
    }
]
Enter fullscreen mode Exit fullscreen mode

The arrow notation is a convenient way to write inline functions like the one above. Also, notice the use of array.includes() function. It will return true if the given array contains the value we pass to it.

In our case, if the currency name is in the required currencies, the filter function will add that currency object to the filteredData.

Alternatively, if you want to use a return statement in the arrow notation, you can use curly braces.

filteredData2 = data.filter((item) => 
    {
        console.log('test');
        return requiredCurrencies.includes(item.name)
    });
Enter fullscreen mode Exit fullscreen mode

This approach is applicable to any situation where you plan to return a value while using arrow notation.

Using Map and ForEach

Now, we want to create an array of label-value pairs from the data. Let the label be the currency name and the value be the current BTC exchange rate for that currency.

We may need such label-value pairs to pass it on to a dropdown select box or some radio/checkbox options.

Let’s assume currencies is the JSON array of all currency codes and rates is the JSON array of the exchange rates for the corresponding currency codes (check the second API). We can get our label value pairs as follows.

LabeledData = currencies.map((item) => {
    return {
        label: item['name'],
        value: rates[item.id]
        }
});
Enter fullscreen mode Exit fullscreen mode

So, array.map executes a function and returns a value for each item of the array. These values are stored in a new array. Here’s what the mapped LabeledData looks like (Showing only the first few items).

[
    {
        "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"
    },
]
Enter fullscreen mode Exit fullscreen mode

This can now be conveniently passed on to a component like a select box or used in some UI rendering. ForEach() can also be used in the exact same way, the difference being, it modifies the original array with returned values and no new array is created.

Using Reduce

Let’s say we have a portfolio JSON which consists of all the cryptocurrencies owned by a user. We want to calculate and show the net worth of their crypto portfolio in USD. Assume you have the USD exchange rate for each cryptocurrency within this JSON.

(Values are dummy values)

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,
    },
]
Enter fullscreen mode Exit fullscreen mode

Simple observation tells us this.

netWorth = sum(quantity * rate)
netWorth = 3*200 + 5*100 + 2*50 + 10*10 = $ 1300
Enter fullscreen mode Exit fullscreen mode

The same operation can be performed on an array using the reduce() function as follows.

initial = 0; //Declare an initial value

netWorth = portfolio.reduce((netValue, item) => netValue + item.quantity*item.rate, initial);

// This computes to networth = 1300
Enter fullscreen mode Exit fullscreen mode

This way, you can compute a single value across the array. The function also takes an initial value to start with.

Summary

  • array.filter((item) => some condition); is used to extract items from an array meeting specific conditions.
  • array.includes(value) returns True if the value is present in the given array.
  • array.map((item) => some function); executes the given function on each item of the array and the corresponding results are stored in a new array.
  • array.forEach((item) => some function); does the same thing as array.map but it modifies the existing array and does not create a new one.
  • array.reduce((value, item) => some function/operation, initialValue); executes the given function for each item in the array and passes on the return value to the next iteration. This way, the return value can be accessed and updated at each iteration giving a final value at the end of the loop.

Top comments (0)