Skip to content
Advertisement

How does one reduce and mutate/change string entries of an array based on common substring patterns?

I have an array of string items …

JavaScript

… and I want to achieve a result like the one below …

JavaScript

Any help is really appreciated.

Advertisement

Answer

  1. Firstly one needs to separate the day value from the hours value part of a single opening hours string.

    • This either can be achieved via indexOf, substring and trim

      JavaScript
    • … or it can be done by split-ting with a Regular Expression like … /(^[^:s]+)s*:s*/ … and slice-ing the results array …

      JavaScript
  2. Then one has to map an entire array of opening hours strings into an array of arrays, where each array-item contains the day value as first and the hours value as second array item … either like this …

    JavaScript

    … or like that …

    JavaScript
  3. On top one needs to reduce this array of splitted [<day>, <hours>] entries into its compact form …

  4. Finally one has to map each splitted [<day>, <hours>] entry with a concatenation task back into its human readable string form….

JavaScript
JavaScript

Another less talkative proof of concept …

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement