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 duplicate values ​by date in JavaScript array

Good afternoon, I need some help to combine the data of this example array taking the position [0] of the date and the position [1] of the name (AA, BB, CC…)

//Origin Array
[
['10/08/2022',  'AA',   '08:00',    '12:00',    '',       '17:00'],
['10/08/2022',  'BB',   '08:01',    '13:15',    '14:16',    '17:01'],
['10/08/2022',  'AA',   ''     ,    ''     ,  '13:00',  ''     ],
['10/08/2022',  'CC',   '09:00',    '11:30',    '12:30',    '18:00']
]

//Result Array
[
['10/08/2022',  'AA',   '08:00',    '12:00',    '13:00',    '17:00'],
['10/08/2022',  'BB',   '08:01',    '13:15',    '14:16',    '17:01'],
['10/08/2022',  'CC',   '09:00',    '11:30',    '12:30',    '18:00']
]

>Solution :

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

You can use reduce method to group the items, and checkValue will combine the filled values only, and Object.values to return it to a multi diminution array after object reduction.

const data = [
['10/08/2022',  'AA',   '08:00',    '12:00',    '',       '17:00'],
['10/08/2022',  'BB',   '08:01',    '13:15',    '14:16',    '17:01'],
['10/08/2022',  'AA',   ''     ,    ''     ,  '13:00',  ''     ],
['10/08/2022',  'CC',   '09:00',    '11:30',    '12:30',    '18:00']
]

const checkValue = (oldItem, newItem) => 
    oldItem ? oldItem.map((item, i) => item || newItem[i]) : newItem

const result = Object.values(data.reduce((acc, item) => 
    ({ ...acc, [item[1]]: checkValue(acc[item[1]], item) }), 
{}))

console.log(result)
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