0

I have the following issue. I have an array of objects and I would like to add the values where the date is equal.

This is the starting array:

0: {date: "07-04-2020", value: 10}
1: {date: "10-04-2020", value: 20}
2: {date: "07-04-2020", value: 30}
3: {date: "14-04-2020", value: 60}

It should result in the following:

0: {date: "07-04-2020", value: 40}
1: {date: "10-04-2020", value: 20}
3: {date: "14-04-2020", value: 60}

I tried some higher order functions, such as filter, map and reduce but I am clueless.

Steve Winter
  • 115
  • 1
  • 6
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Apr 14 '20 at 14:34
  • 1
    See https://stackoverflow.com/questions/43281272/merge-objects-in-array-based-on-property and several others from [this search](/search?q=%5Bjs%5D+merge+objects+in+array). More about searching [here](/help/searching). – T.J. Crowder Apr 14 '20 at 14:35
  • `var foo = [{date: "07-04-2020", value: 10}, {date: "10-04-2020", value: 20}, {date: "07-04-2020", value: 30}, {date: "14-04-2020", value: 60}];` `var bar = {};` `foo.forEach(i => { if(bar[i.date]) { bar[i.date] += i.value} else {bar[i.date] = i.value} })` - then map them back to your original structure – developer Apr 14 '20 at 14:40
  • map back with `Object.keys(bar).map(k => { return {date: k, value: bar[k]}})` – developer Apr 14 '20 at 14:47

2 Answers2

1

You could use Array.reduce:

[...].reduce((acc, next) => {
  // Check if an item with the given date exists
  const existingItem = acc.find(item => item.date === next.date);
  // If not, add the new one to the array
  if (!existingItem) {
    return [...acc, next];
  }
  // If there's one already, mutate the value property and return everything
  existingItem.value += next.value;
  return acc;
}, []);
sandrooco
  • 8,016
  • 9
  • 48
  • 86
0

Will this work for you?

let myArr = [{
    date: "07-04-2020",
    value: 10
  },
  {
    date: "10-04-2020",
    value: 20
  },
  {
    date: "07-04-2020",
    value: 30
  },
  {
    date: "14-04-2020",
    value: 60
  },
]

function sum(arr) {
  let result = [];
  let temp = {};

  arr.forEach((row) => {
    temp[row.date] = temp[row.date] ? temp[row.date] + row.value : row.value;
  });

  Object.entries(temp).forEach((dateValue) => {
    result.push({
      date: dateValue[0],
      value: dateValue[1]
    });
  });

  return result;
}
console.log(sum(myArr));
kiranvj
  • 32,342
  • 7
  • 71
  • 76