1

I have an array of below objects

[
  {
    "date": "2021-07-24",
    "model": "Benz",
    "bookings": 3
  },
  {
    "date": "2021-07-24",
    "model": "BMW",
    "bookings": 4
  },
  {
    "date": "2021-07-24",
    "model": "Audi",
    "bookings": 1
  },
  {
    "date": "2021-07-25",
    "model": "Benz",
    "bookings": 5
  },
  {
    "date": "2021-07-25",
    "model": "BMW",
    "bookings": 7
  },
  {
    "date": "2021-07-25",
    "model": "Audi",
    "bookings": 3
  }
]

How do I convert the same after grouping as the below one in js?

Expected:

[
  {
    "date": "2021-07-24",
    "Benz": 3,
    "BMW": 4,
    "Audi": 1
  },
  {
    "date": "2021-07-25",
    "Benz": 5,
    "BMW": 7,
    "Audi": 3
  }
]

Idea on implementing it would be much helpful. Tried implementing a different approach of grouping as referred here

But the above case mentioned as expected output suits the purpose well

ikhvjs
  • 5,316
  • 2
  • 13
  • 36
CodeWiz
  • 13
  • 3

1 Answers1

0

You can use reduce() with a Map object.

Edit:

data.reduce() will return a Map Object and you can use .values() to get the values of the Map object.

Then you can use the spread operator ... to get the values of Map object in an array.

In short:

const output = [...data.reduce().values()]

Example below:

const data = [ { date: "2021-07-24", model: "Benz", bookings: 3, }, { date: "2021-07-24", model: "BMW", bookings: 4, }, { date: "2021-07-24", model: "Audi", bookings: 1, }, { date: "2021-07-25", model: "Benz", bookings: 5, }, { date: "2021-07-25", model: "BMW", bookings: 7, }, { date: "2021-07-25", model: "Audi", bookings: 3, }, ];

const o = [
  ...data
    .reduce((a, b) => {
      if (a.has(b.date)) {
        const obj = a.get(b.date);
        if (obj[b.model]) {
          obj[b.model] += b.bookings;
        } else {
          obj[b.model] = b.bookings;
        }
        a.set(b.date, obj);
      } else {
        a.set(b.date, { date: b.date, [b.model]: b.bookings });
      }
      return a;
    }, new Map())
    .values(),
];

console.log(o);
ikhvjs
  • 5,316
  • 2
  • 13
  • 36