0

I have an array with a lot of elements. Each element is like:

e1 = { data: 12345, month: 8, year: 2018 }

And with this array I want to create a new array of elements of the same type but with the sum of each data of the element which have the same month and the same year.

For example: If my array is:

myArray = [
    {
        data: 1,
        month: 7,
        year: 2018
    },
    {
        data: 2,
        month: 8,
        year: 2018
    },
    {
        data: 3,
        month: 8,
        year: 2018
    }
]

I want this new array:

myNewArray = [
    {
        data: 1,
        month: 7,
        year: 2018
    },
    {
        data: 5,
        month: 8,
        year: 2018
    }
]

Could you help me with that by using javascript function ?

Adrien
  • 2,866
  • 4
  • 23
  • 46

1 Answers1

0

You can use reduce to index elements by month and year and increment data as you find new elements:

var myArray = [{
    data: 1,
    month: 7,
    year: 2018
  },
  {
    data: 2,
    month: 8,
    year: 2018
  },
  {
    data: 3,
    month: 8,
    year: 2018
  }
];

var grouped = myArray.reduce((acc, curr) => {
  var key = `${curr.year},${curr.month}`;
  if (!(key in acc)) acc[key] = Object.assign({}, curr);
  else acc[key].data += curr.data;
  return acc;
}, {});

console.log(Object.values(grouped));
slider
  • 12,810
  • 1
  • 26
  • 42
  • That's gotta be the most unreadable javascript snippet i've ever seen. Please consider using semantic name for variable and parameters – Jorel Amthor Nov 21 '18 at 16:23
  • @JorelAmthor `acc` and `curr` are standard names for the arguments for the `reduce` callback: It's even in the official doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description – slider Nov 21 '18 at 16:29
  • @slider - I'll come to your defense that `acc`/`curr` are fine var names to use, but please note that, while extremely useful, MDN is not the "official doc"-- Mozilla doesn't somehow own JavaScript. – Alexander Nied Nov 21 '18 at 16:31