Home > Blockchain >  Grouping Array of items in an Array
Grouping Array of items in an Array

Time:11-05

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?

CodePudding user response:

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);

CodePudding user response:

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);

CodePudding user response:

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;
  }, {});
  • Related