M
M
mamaanarhiya2018-02-14 16:44:36
JavaScript
mamaanarhiya, 2018-02-14 16:44:36

How to create such an array with data?

There is an array like:

[{value: 123, title: 'test'},{value: 321, title: 'test2'},{value: 1232312, title: 'test2'},{value: 5678, title: 'test2'}]

How to make such an array from it?
[
    {
      title: 'test',
      data: [
        {
          money: 123,
        },
      ],
    },
    {
      title: 'test2',
      data: [
        {
          money: 321,
        },
        {
          money: 1232312,
        },
        {
          money: 5678,
        },
      ],
    },
  ]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-14
@mamaanarhiya

const groupedData = Object.values(data.reduce((acc, { title, value }) => {
  (acc[title] = acc[title] || { title, data: [] }).data.push({ money: value });
  return acc;
}, {}));

or
const groupedData = arr.reduce((acc, { title, value }) => {
  let g = acc.find(n => n.title === title);
  if (!g) {
    acc.push(g = { title, data: [] });
  }
  g.data.push({ money: value });
  return acc;
}, []);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question