1

I have a big array with data. Here is a example of the structure:

let data = [
  {
    date: '2018-11-22',
    values: {
      a: 10,
      b: 20,
      c: 5,
    },
  },
  {
    date: '2018-11-17',
    values: {
      a: 5,
      b: 10,
      c: 15,
    },
  },
  {
    date: '2018-06-29',
    values: {
      a: 10,
      b: 30,
      c: 10,
    },
  },
  {
    date: '2017-12-20',
    values: {
      a: 30,
      b: 40,
      c: 5,
    },
  },
];

I need this data structured in a new array by month and year. The value attributes should be summed up for each month.

So the new array for the example should look like this:

let sortedData = [
  {
    date: '2018-11',
    values: {
      a: 15,
      b: 30,
      c: 20,
    },
  },
  {
    date: '2018-06',
    values: {
      a: 10,
      b: 30,
      c: 10,
    },
  },
  {
    date: '2017-12',
    values: {
      a: 30,
      b: 40,
      c: 5,
    },
  },
];

I'm trying for hours to write a working function but I can't handle it. Any ideas how I can bundle an array like this?

Thanks for your help!

2 Answers 2

4

You can use Array.reduce for this

let data = [  {    date: '2018-11-22',    values: {      a: 10,      b: 20,      c: 5,    },  },  {    date: '2018-11-17',    values: {      a: 5,      b: 10,      c: 15,    },  },  {    date: '2018-06-29',    values: {      a: 10,      b: 30,      c: 10,    },  },  {    date: '2017-12-20',    values: {      a: 30,      b: 40,      c: 5,    },  },];

let res = data.reduce((o, {date, values}) => {
  let k = date.slice(0, 7)
  
  o[k] = o[k] || {date: k, values: {a: 0, b: 0, c:0}}
  o[k].values.a += values.a
  o[k].values.b += values.b
  o[k].values.c += values.c
  
  return o
}, {})

console.log(Object.values(res))

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

2 Comments

Is there a way to bundle months in an array and not in an object?
@iamrobin. Yes possible. Can you pls tell expected output?
1

You can also do make it more concise and not deal with the individual values props like this:

let data = [{ date: '2018-11-22', values: { a: 10, b: 20, c: 5, }, }, { date: '2018-11-17', values: { a: 5, b: 10, c: 15, }, }, { date: '2018-06-29', values: { a: 10, b: 30, c: 10, }, }, { date: '2017-12-20', values: { a: 30, b: 40, c: 5, }, }, ];

const result = data.reduce((r, {date, values}) => {
  date = date.substr(0,7)
  r[date] = r[date] 
   ? (Object.keys(values).forEach(k => r[date].values[k] += values[k]), r[date])
   : {date, values}
  return r
}, {})

console.log(Object.values(result))

This way you would not care if there are 3 of 10 properties in values and you get more generic solution.

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.