-1

I have two array and I want to merge this two array and sum the value by date

here are the example arrays

const lz = [
  {
    date: "2020-05",
    value: 100
  },
  {
    date: "2020-06",
    value: 200
  }
]

const sp = [
  {
    date: "2020-05",
    value: 150
  },
  {
    date: "2020-06",
    value: 250
  }
]

the result should be the sum of two arrays

const data = [
  { date: "2020-05", value: 250 },
  { date: "2020-06", value: 450 }
]
jdxcode
  • 23
  • 4
  • 1
    What have you tried so far to solve this on your own? And what's the problem with that approach? – Andreas Oct 05 '20 at 09:23
  • stack overflow expects you to show how you attempted to solve your problem - you would use various array methods, most likely array reduce – Jaromanda X Oct 05 '20 at 09:23
  • Also, Stack Overflow expects you to first research your problem. In 5 seconds searching the internet many hits with solutions pop up. – trincot Oct 05 '20 at 09:24
  • `const data=Array.from([...lz, ...sp].reduce((a,{date,value})=>(a.set(date,(a.get(date)||0)+value),a),new Map).entries(),([date,value])=>({date,value}));` – Jaromanda X Oct 05 '20 at 09:38

1 Answers1

1

You could first spread both arrays into one and then reduce it

const lz = [
  {
    date: "2020-05",
    value: 100
  },
  {
    date: "2020-06",
    value: 200
  }
]

const sp = [
  {
    date: "2020-05",
    value: 150
  },
  {
    date: "2020-06",
    value: 250
  }
]

function merge(arr1,arr2){
   return [...arr1, ...arr2].reduce((a,v) => {
      let index = a.findIndex(({date}) => date === v.date);
      if(index !== -1) {
         a[index].value += v.value;
         return a;
      }
      return [...a, { date:v.date, value: v.value }]
   },[])
}

console.log(merge(sp, lz))
bill.gates
  • 14,145
  • 3
  • 19
  • 47