I have one array which has two values one date and an amount but there is the same date with a different value at a different index so I need to merge those values into the same date in a multidimensional javascript array
current array
var arry = [
['2021-05-01',100],
['2021-05-02',300],
['2021-05-03',200],
['2021-05-01',150],
['2021-05-02',300],
['2021-05-01',600],
['2021-05-04',120]
]
Expected Result Array
var arry = [
['2021-05-01',850],
['2021-05-02',600],
['2021-05-03',200],
['2021-05-04',120]]
Can anybody help? I really appreciate any help you can provide.
>Solution :
Here is a solution using reduce. I’m creating an object grouped by date and taking the values array of it
var arry = [['2021-05-01',100], ['2021-05-02',300], ['2021-05-03',200], ['2021-05-01',150],['2021-05-02',300], ['2021-05-01',600],['2021-05-04',120]]
const res = Object.values(arry.reduce((acc,[date,val])=> {
acc[date] = acc[date] || [date,0]
acc[date][1]+=val
return acc
},{}))
console.log(res)