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 :
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)