Task M2

Write a function that takes an array of transaction objects as input, process all the duplicate transactions and segregate them in separate arrays. Function shall return an array of array of duplicate transactions only.

by vaheed akhtar

JavaScript

let transactions = [
{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:30.000Z'
},
{
id: 1,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
},
{
id: 6,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 4,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:36:00.000Z'
},
{
id: 2,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,

category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 5,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:00.000Z'
}
];

function returnDuplicates(arr) {
  return arr.map(tran => ({
    key: JSON.stringify([tran.sourceAccount, tran.targetAccount, tran.amount, tran.category]), 
    tran_time: Date.parse(tran.time), tran
})).sort((i,j) => i.key.localeCompare(j.key) || i.tran.id - j.tran.id || i.tran_time - j.tran_time
).reduce(([acc, prev], cur) => {
    if (!prev || cur.key != prev.key || cur.tran_time - prev.tran_time > 60000) acc.push([]);
    acc[acc.length-1].push(cur.tran);
    return [acc, cur];
}, [[]])[0].filter(a => a.length > 1);
}

returnDuplicates(transactions);