Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine value with same date in multidimensional array in Javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading