Search code examples
javascriptarraysreactjsmapreducejavascript-objects

React, ordering and array of objects (reduce and map?)


the issue is as follows: (https://codesandbox.io/s/8p21n6p09l)

I've got an array of objects (called modules) that looks like that:

const modules = [
  {
    thematicArea: "Topic 1",
    id: 1,
    name: "Budowanie postawy asertywnej",
    details: [
      "Czym jest asertywność?",
      "Asertywny Asertywny menedżer – charakterystyczne zachowania"
    ]
  },
  {
    thematicArea: "Topic 2",
    id: 2,
    name: "Asertywne narzędzia",
    details: [
      "Asertywna odmowa – zastosowanie trzyetapowej procedury",
      "Technika „Zdartej płyty”",
      "Wyrażanie pochwał i próśb"        ]
  },
  {
    thematicArea: "Topic 3",
    id: 3,
    name: "Lorem ipsum 1",
    details: ["Coś się wymyśli", "Żeby nie było tak łyso"]
  },
  {
    thematicArea: "Topic 3",
    id: 4,
    name: "Lorem ipsum 2",
    details: [
      "Wyczesane szkolenia",
      "Naprawdępowinieneś wrzucić to do koszyka",
      "Na co czekasz - dodaj!"
    ]
  },
  {
    thematicArea: "Topic 3",
    id: 5,
    name: "Ipsum Lorem",
    details: ["Och", "Ach"]
  },
  {
    thematicArea: "Topic 3",
    id: 6,
    name: "Ipsum Lorem 1",
    details: ["Och", "Ach"]
  },
  {
    thematicArea: "Topic 3",
    id: 7,
    name: "Ipsum Lorem 2",
    details: ["Och", "Ach"]
  },

and this array is passed from App.js to thmaticArea.jsx component. The thing is that I've changed my mind in displaying data and want group them by thematicArea, so it'd look like:

Topic 1: 
 - Name 1
 - Name 2
 - Name 6
 - ...
Topic 2:
 - Name 3
 - Name 5
Topic 3:
- Name 4
and so on.

Each Name is unique and can have only one thematicArea (Topic) but one thematicArea (Topic) can have multiple names (Name 1, Name 2...).

I believe I should use reduce() method first and .map() then, but I've tried it in multiple ways and it doesn't worked for me. Reduce() method is creating an array with no length... This is how I tried to implement it with reduce in App.js and pass it to thematicArea.jsx component as 'modules':

modules={this.state.modules.reduce(function(groups, item) {
              const val = item["thematicArea"];
              groups[val] = groups[val] || [];
              groups[val].push(item);
              return groups;
            }, [])}

What is the best way to achieve the expected result?


Solution

  • If this isn't a theoretical programming question I think the best way is to use _.groupBy from lodash or similar. Reinventing the wheel in not needed sometimes.