0

I'm trying to restructure the data I get from graphql base on its Date value. I will map that array to display some type of feed or a list of the next events. Dates don't carry out any importance here it is just grouping and in sample data, I replaced the long date formating with days to make it easier.

So here is a sample Data:

[{
  "__typename": "Session",
  "date": "Monday",
  "id": "6180da7e1478f62322df638b",
},
{
  "__typename": "Session",
  "date": "Wednesday",
  "id": "6180da7f1478f62322df638c",
},
{
  "__typename": "Session",
  "date": "Wednesday",
  "id": "6180da7f1478f62322df638d",
}]

I'm trying to create a new array with

[ 
 {
  "date": "Monday",
  "sessions":[
   {
    "__typename": "Session",
    "date": "Monday",
    "id": "6180da7e1478f62322df638b",
   }
  ]
 },
 { 
  "date": "Wednesday",
  "sessions": [
   {
    "__typename": "Session",
    "date": "Wednesday",
    "id": "6180da7f1478f62322df638c",
   },
   {
    "__typename": "Session",
    "date": "Wednesday",
    "id": "6180da7f1478f62322df638d",
   }
  ]
 },
]

I have tried array.reduce(), but no luck so far, anybody has any suggestion?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Bora ALAP
  • 269
  • 3
  • 13

3 Answers3

1

Not the fanciest solution, but it should work

const mapped = {};
sampleData.forEach((d) => {
  mapped[d.date] = mapped[d.date] || {
    date: d.date,
    sessions: [],
  };

  mapped[d.date].sessions.push(d);
});

const mappedArray = Object.values(mapped);
westmark
  • 909
  • 8
  • 15
0

I am trying to solve this issue, by the below code.

Step 1:- Import the lodash lib and group the item based on Date from an array

var _ = require("lodash");

let grouped = array.reduce((total, item) => {
  (total[item.date] = total[item.date] || []).push(item);
  return total;
}, {});

Step 2:- Combined the grouped array into new Object

const combinedArray = array.map((item) => {
  let combinedArray = { date: item.date, sessions: grouped[item.date] };
  return combinedArray;
});

Step 3:- Remove the duplicates using lodash (there is another javascript function also available)

let result = _.uniqBy(combinedArray, "date");
console.log(result);
omprakash8080
  • 1,211
  • 16
  • 11
-1

You can use this function to group by a key in the array;

const groupBy = (array, key) => {
  const grouped = array.reduce((result, currentValue) => {
    (result[currentValue[key]] = result[currentValue[key]] || []).push(
      currentValue
    );
    return result;
  }, {});