0

So let's say I have an array of objects

const data = [{ description: "my frist event", start_time: "11:00", end_time: "12:00", event_day: "22" }, { description: "my second event", start_time: "11:00", end_time: "12:00", event_day: "22" }]

So for every day, there will be an array of objects. For example, day 22 should have two items in the array. So the structure to be in this format

{ 22: [ { description: 'my second event',
   start_time: '11:00',
   end_time: '12:00',
   event_day: '22' }, { description: "my frist event", start_time: "11:00", end_time: "12:00", event_day: "22" } ] }

using the reduce method

const arrayToObject = (array) =>array.reduce((obj, item) => {
  obj[item.event_day] = [item]
  return obj}, {})
arrayToObject(data)

gives me the following output:

{ 22: [ { description: 'my second event',
   start_time: '11:00',
   end_time: '12:00',
   event_day: '22' } ] }

This only adds the last item to the array. Is there a way to add all another objects to the array?

1
  • Your callback has to check to see if obj[item.event_day] already exists. Commented Jun 25, 2018 at 23:38

2 Answers 2

3

If the array corresponding to the event_day doesn't exist in the accumulator object, create it first, and then push to it:

const data = [{ description: "my frist event", start_time: "11:00", end_time: "12:00", event_day: "22" }, { description: "my second event", start_time: "11:00", end_time: "12:00", event_day: "22" }];
const groupedByDay = data.reduce((a, item) => {
  const { event_day } = item;
  if (!a[event_day]) a[event_day] = [];
  a[event_day].push(item);
  return a;
}, {});
console.log(groupedByDay);

Sign up to request clarification or add additional context in comments.

Comments

0

this should work also:

const data = [
  {
    description: 'my frist event',
    start_time: '11:00',
    end_time: '12:00',
    event_day: '22',
  },
  {
    description: 'my second event',
    start_time: '11:00',
    end_time: '12:00',
    event_day: '22',
  },
  {
    description: 'my second event',
    start_time: '11:00',
    end_time: '12:00',
    event_day: '55',
  },
];

const reduced = data.reduce(
  (acc, item) => ({
    ...acc,
    [item.event_day]: data.filter((i) => i.event_day === item.event_day),
  }),
  {}
);

console.log('reduced', reduced);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.