Home > Blockchain >  Combine duplicate values ​by date in JavaScript array
Combine duplicate values ​by date in JavaScript array

Time:08-31

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']
]

CodePudding user response:

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)

CodePudding user response:

I'll give you a brute force answer. As others have noted, functions exist to improve it.

First I'll check if the date/name pair already exists. If not, just add the data. If it did, then update the blanks.

originalArray = <your data>
resultArray = []

function findDateNamePair(resultArray, aDate, aName) {
    // return index if resultArray[index][0] = aDate and resultArray[index][1] = aName
    // return -1 if not found

    for (var i=0; i < resultArray.length; i  ) {
        if (resultArray[i][0] == aDate && resultArray[i][1] == aName) {
            return i;
        }
    }
    return -1;
}

for (var i=0; i < originalArray.length; i  ) {
    const thisEntry = originalArray[i];
    const existingIndex = findDateNamePair(resultArray, thisEntry[0], thisEntry[1]);
    if (existingIndex == -1) {
        resultArray.push(thisEntry);
    }
    else {
        for (var j=2; j<=5; j  ) {
            if (resultArray[existingIndex][j] == '') {
                resultArray[existingIndex][j] = thisEntry[j];
            }
        }
    }
}
  • Related