Search code examples
javascriptreactjslodash

Get currencies from countries list with lodash/fp


How can I get an array of currencies with each currencySimbol from this array of countries with Lodash? I used to have this getCurrencies function, but I can't get the Symbols with it, so now I made this getCurrenciesWithSymbol but it's making duplicates and stuff like this {key: "", displayName: "", currencySymbol: undefined}

import { flow, map, uniq, keyBy, compact, pick } from "lodash/fp";


const countries = [
  {
    key: "US",
    name: "United States",
    currency: "USD",
    currencySymbol: "$"
  },
  {
    key: "TW",
    name: "Taiwan",
    currency: "TWD",
    currencySymbol: ""
  }
];


function getCurrencies(countries) {
  const currencies = flow(
    map("currency"),
    uniq,
    compact,
    map((each) => ({ key: each, displayName: each }))
  )(countries);

  return {
    asList: currencies,
    byKey: keyBy("key", currencies)
  };
} // [{key: "USD", displayName: "USD"}, {key: "TW", displayName: "TW"}]


function getCurrenciesWithSymbol(countries) {
  const currencies = flow(
    map(pick(["currency", "currencySymbol"])),
    uniq,
    compact,
    map((each) => ({
      key: each.currency,
      displayName: each.currency,
      currencySymbol: each.currencySymbol
    }))
  )(countries);

  return {
    asList: currencies,
    byKey: keyBy("key", currencies)
  };
}

//Expected
// [
//   { displayName: "USD", key: "USD", currencySymbol: "$" },
//   { displayName: "TW", key: "TW", currencySymbol: "" }
// ];

Solution

  • Use _.uniqBy('currency') to dedupe the array, and then map to the requested form:

    const { flow, uniqBy, map } = _;
    
    const getCurrenciesWithSymbol = flow(
      uniqBy('currency'),
      map(({ currency, currencySymbol }) => ({
        displayName: currency,
        key: currency,
        currencySymbol
      }))
    );
    
    const countries = [{"key":"US","name":"United States","currency":"USD","currencySymbol":"$"},{"key":"TW","name":"Taiwan","currency":"TWD","currencySymbol":""}];
    
    const result = getCurrenciesWithSymbol(countries);
    
    console.log(result);
    <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>